Sorting arrays in JavaScript has one famous trap, and copying arrays has one famous rule. The copy that you get is only as deep as you asked for. This lesson covers the comparator function that fixes the trap, the newer methods that sort without changing anything, and which copy technique to reach for when your array contains objects.
The previous lesson in this module covered "filter, find and reduce: The Search-and-Aggregate Trio", and this lesson is the last one in the JavaScript Array Methods module.
Why does sorting numbers give the wrong answer?
Because Array.prototype.sort turns every element into text and then compares those texts. That is exactly right for a list of words and completely wrong for a list of numbers, because '100' comes before '9' as text.
const scores = [10, 9, 100, 1];
const asText = scores.slice().sort();
console.log(asText); // [ 1, 10, 100, 9 ]
const byNumber = scores.slice().sort(function (a, b) {
return a - b;
});
console.log(byNumber); // [ 1, 9, 10, 100 ]
The first result is not a bug in the engine. It is the documented default. The fix is to pass a comparator function, which is a function that receives two elements and returns a negative number when the first one should come first, a positive number when it should come second, and zero when the two are equivalent. Subtracting them is the standard shortcut, and it works for numbers, for dates, and for anything else that you can subtract.
How do you sort objects by a field?
The same comparator rule applies, except that now each side of the comparison is an object and you choose which field to compare. Add a second comparison with || to break ties, which is how you get a stable and predictable order when two records share the same score.
const players = [
{ name: 'Asha', score: 42 },
{ name: 'Bala', score: 91 },
{ name: 'Chen', score: 91 },
];
players.sort(function (a, b) {
return b.score - a.score || a.name.localeCompare(b.name);
});
for (const player of players) {
console.log(player.name + ':' + player.score);
}
// Bala:91
// Chen:91
// Asha:42
Read the comparator from left to right. It sorts by score descending first, and when the scores are equal, which is when the subtraction returns 0 and that value is falsy, it falls through to the name comparison. That tie-break is what keeps the output stable between runs and between different engines.
A frequent mistake is writing the comparator as a boolean expression, such as function (a, b) { return a.score > b.score; }. A boolean is not a number, so the engine treats every result as zero and the array keeps its original order. The comparator has to return a number, and subtracting the two values is the cheapest way to produce one.
What about sorting text?
For strings, localeCompare is the right tool. The default text comparison uses character codes, which puts every capital letter before every lowercase one. That is why 'B' sorts before 'a', and it is also why any accented or non-Latin text ends up in the wrong place.
console.log(['a', 'B'].sort()); // [ 'B', 'a' ]
console.log(['a', 'B'].sort(function (x, y) {
return x.localeCompare(y);
})); // [ 'a', 'B' ]
console.log(['Zoe', 'ada', 'Bob'].sort(function (x, y) {
return x.localeCompare(y);
})); // [ 'ada', 'Bob', 'Zoe' ]
The last result is the payoff. With a locale-aware comparison the list reads like the alphabetical list that a human would expect, instead of being grouped by capitalisation.
What is the difference between sort and toSorted?
sort rewrites the array that you call it on. toSorted returns a sorted copy and leaves the original alone, and there are matching methods called toReversed and toSpliced. These newer methods make "sort without side effects" a one-liner instead of the copy-then-sort dance.
const original = [3, 1, 2];
const ascending = original.toSorted(function (a, b) {
return a - b;
});
const reversed = original.toReversed();
const cut = original.toSpliced(1, 1);
console.log(original); // [ 3, 1, 2 ]
console.log(ascending); // [ 1, 2, 3 ]
console.log(reversed); // [ 2, 1, 3 ]
console.log(cut); // [ 3, 2 ]
The original array is still [3, 1, 2] at the end, and that is exactly the guarantee that you want when the array came from a function argument or from application state. If you need to support older browsers, then arr.slice().sort() is the equivalent one-liner.
The same split applies to reversing. arr.reverse() rewrites the array in place, while arr.toReversed() gives you a reversed copy. One naming habit is worth adopting. If the method name starts with to, then it returns a new value and leaves the original alone.
Which copy should you use, slice or spread?
For an array of plain values such as strings, numbers, and booleans, both slice() and the spread syntax give you a new array with the same items, and neither one is connected to the original.
const original = [3, 1, 2];
const copy = original.slice();
copy.push(4);
console.log(original); // [ 3, 1, 2 ]
console.log(copy); // [ 3, 1, 2, 4 ]
const spread = [...original];
console.log(spread === original); // false
slice is the older, method-based spelling, and the spread syntax is the newer one. The spread syntax does more than copy, because it can also merge arrays. Pick either one for a flat list, and keep reading for the moment when the items are objects.
What happens when the array holds objects?
Both copy techniques are shallow. The new array is a different array, but the items inside it are the same objects, so changing one of those objects changes the original as well.
const config = { list: [1, 2] };
const shallow = { ...config };
shallow.list.push(3);
console.log(config.list); // [ 1, 2, 3 ]
const deep = structuredClone(config);
deep.list.push(9);
console.log(config.list); // [ 1, 2, 3 ]
console.log(deep.list); // [ 1, 2, 3, 9 ]
The first three lines show the shallow trap. shallow.list and config.list are the same array, so the push shows up in both of them. The structuredClone function, which is built into the platform, copies the nested structure as well, and that is why the final lines show config.list untouched by the change to deep.list. The objects module goes into reference behaviour properly. For now, the rule is that a one-level copy is enough for arrays of simple values and not enough for arrays of objects.
Which copy technique should I reach for?
| Technique | Copies one level? | Copies deeply? | Mutates the original? |
|---|---|---|---|
arr.slice() | Yes | No | No |
[...arr] | Yes | No | No |
structuredClone(x) | Yes | Yes | No |
arr.sort() | No | No | Yes |
arr.toSorted() | Yes | No | No |
Try it yourself: write a file called leaderboard.js with the players array above. Sort it by score descending with a name tie-break, and print it. Then sort a copy by name ascending with localeCompare and print that, checking that the first array is unchanged afterwards. Finally, build a shallow copy of the players array with the spread syntax, change copy[0].score to zero, and print the original array's first score. Notice that it changed too. Then repeat it with structuredClone and watch it stay where it was.