To create a JavaScript array of integers in descending order, you can use the sort()
method in combination with a comparison function that compares each element with its adjacent element and swaps their positions if they are out of order. Here’s an example:
let nums = [4, 2, 8, 1, 5];
nums.sort(function(a, b) {
return b - a;
});
console.log(nums); // [8, 5, 4, 2, 1]
In the example above, the sort()
method is called on the nums
array with a comparison function that takes two parameters a
and b
. The function returns the result of subtracting b
from a
, which determines the order of the two elements being compared. If the result is negative, a
comes before b
; if the result is positive, b
comes before a
; and if the result is zero, the order of the two elements is unchanged.
By returning b - a
, we are effectively sorting the array in descending order. The sorted array is then printed to the console using the console.log()
method.