JavaScript · Level 2 Arrays

Sorting with Compare Functions

Order numbers and product lists correctly by handing sort a compare function, and sort a copy so the caller's array stays as it was.

  • sort() compares items as text by default
  • Compare functions (a, b) => a - b
  • sort() changes the array; copy it first with [...arr]

Two traps: sort() compares items as text, so 10 comes before 9, and unlike map, it changes the array. Pass a compare function (negative means a first) and sort a copy.

const nums = [10, 9, 1];

[...nums].sort();                  // [1, 10, 9] — text order!
[...nums].sort((a, b) => a - b);   // [1, 9, 10]
[...nums].sort((a, b) => b - a);   // [10, 9, 1]
nums.sort((a, b) => a - b);        // nums itself is now [1, 9, 10]

Write sortByPrice(products) that returns a new array sorted by price, cheapest first, without changing products; prices [100, 9, 10] come out as [9, 10, 100].

solution.js
Test Suites Pending
Output