JS Array Sort
JavaScript Array Sort: Numbers, Strings, and Objects
JavaScript sort() arranges elements alphabetically as strings by default, which surprises developers when sorting numbers. Providing a short comparator function fixes numeric sorting, and ES2023 toSorted() keeps your original array untouched.
Why [10, 2, 1].sort() Gives [1, 10, 2]
Without a comparator, sort() converts every element to a string and compares UTF-16 character codes. Because "10" starts with "1", "10" comes before "2".
To sort numbers properly, pass a compare function (a, b) => a - b for ascending order or (a, b) => b - a for descending order.
Sorting Numbers, Strings, and Objects Safely
Use toSorted() (or [...arr].sort(...)) when you do not want to mutate the original array in place.
const scores = [40, 100, 1, 5, 25];
const ascending = scores.toSorted((a, b) => a - b);
const descending = scores.toSorted((a, b) => b - a);
console.log("Original:", scores);
console.log("Ascending:", ascending);
console.log("Descending:", descending);
const products = [
{ name: "Keyboard", price: 75 },
{ name: "Mouse", price: 30 },
{ name: "Monitor", price: 240 },
];
const byPrice = products.toSorted((a, b) => a.price - b.price);
const byName = products.toSorted((a, b) => a.name.localeCompare(b.name));
console.log("By price:", byPrice.map((p) => p.name));
console.log("By name:", byName.map((p) => p.name));
Common Mistakes to Avoid
- Calling
numbers.sort()without a comparator: Always supply(a, b) => a - bwhen sorting numeric arrays. - Mutating React or Redux state with
sort():arr.sort()modifiesarrin place and returns the same reference. Copy with[...arr].sort()or usearr.toSorted(). - Comparing strings with
a - b: Subtracting strings yieldsNaN. Usea.localeCompare(b)for alphabetical sorting across accented characters.
Frequently Asked Questions
How do I reverse an array without changing the original?
Use ES2023 arr.toReversed(), or clone first with [...arr].reverse(). Calling arr.reverse() directly mutates the original array.
How does the comparator return value work?
If (a, b) returns a negative number, a comes before b. If positive, b comes before a. If 0, their relative order stays unchanged.
Is JavaScript Array.prototype.sort() stable?
Yes, since ES2019 all major engines implement a stable sort, keeping equal items in their original relative order.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.