JS Built-ins
← Array179 / 226
ArrayArray.prototype.sortintermediate

Array.prototype.sort() β€” numeric descending

πŸ“– Usage Example
const nums = [3, 1, 4, 1, 5]
nums.sort((a, b) => b - a)  // β†’ [5, 4, 3, 1, 1]

Swap the arguments in the comparator (b - a) to sort numbers in descending order.

Array.prototype.sort() β€” descending order

To sort numbers in descending order, reverse the comparator: (a, b) => b - a.

Challenge: Implement sortDesc(nums) that sorts a copy of the array in descending numeric order.

sortDesc([3, 1, 4, 1, 5]) // β†’ [5, 4, 3, 1, 1]
sortDesc([10, 9, 2])      // β†’ [10, 9, 2]
πŸ’‘ Hints (2)
  • β€’ Swapping `a` and `b` in the subtraction flips the sort order.
  • β€’ You can also sort ascending then call `.reverse()`, but `(a, b) => b - a` is cleaner.