Sorting Arrays
sort changes the array in place and sorts as text by default, so 10 comes before 2. Pass a compare function (a, b) => a - b to sort numbers properly. reverse flips the order.
Use toSorted or a copy ([...arr].sort()) when you must keep the original.
Example
const nums = [10, 2, 33, 4];
console.log([...nums].sort());
console.log([...nums].sort((a, b) => a - b));
console.log([...nums].sort((a, b) => b - a));
const people = [{ n: "Tunde", age: 30 }, { n: "Ada", age: 21 }];
console.log(people.sort((a, b) => a.age - b.age).map((p) => p.n));Exercise
Sort numbers from low to high.
nums.sort((a, b) => a b);
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.