Beginner · 9 min
Sort numbers deliberately
Use a numeric comparator and preserve the original array when needed.
Choose numeric order
sort() compares strings by default. For ascending numeric order, pass a comparator that returns a negative, zero, or positive number.
const values = [10, 2, 8];
console.log([...values].sort().join(", "));
console.log([...values].sort((a, b) => a - b).join(", "));Output
10, 2, 8 2, 8, 10
Keep the original
sort() changes its array. Copy first with spread when you need to keep the original order. Reverse the subtraction for descending numeric order.
const scores = [5, 9, 3];
const ranked = [...scores].sort((a, b) => b - a);
console.log(scores.join(", "));
console.log(ranked.join(", "));Output
5, 9, 3 9, 5, 3
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Rank scores
Sort a copy of scores from highest to lowest, then display ranked. Leave scores in its original order.
Use (a, b) => b - a as the comparator.