JS Built-ins
← Array178 / 226
ArrayArray.prototype.sortbeginner

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

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

Always pass a numeric comparator (a - b) to sort() when sorting numbers.

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

Without a comparator, sort() converts numbers to strings which causes incorrect ordering (e.g. 10 comes before 9). Pass (a, b) => a - b to sort numerically ascending.

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

sortAsc([3, 1, 4, 1, 5]) // β†’ [1, 1, 3, 4, 5]
sortAsc([10, 9, 2])      // β†’ [2, 9, 10]
πŸ’‘ Hints (2)
  • β€’ The comparator `(a, b) => a - b` returns negative when `a < b`, 0 when equal, positive when `a > b`.
  • β€’ Always copy first with `.slice()` unless you intentionally want to mutate the original.