Sorting Arrays Correctly
sort converts items to strings by default, so numbers sort wrongly. Pass a compare function: (a, b) => a - b. toSorted returns a sorted copy.
Example
const n = [10, 9, 1, 100];
console.log([...n].sort(), [...n].sort((a, b) => a - b));
const people = [{ n: "Zed", a: 20 }, { n: "Ada", a: 30 }];
console.log(people.toSorted((x, y) => x.n.localeCompare(y.n)).map((p) => p.n));Exercise
Numeric ascending order.
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.