Array Sort
Master this topic with zero to advance depth.
Expert Answer & Key Takeaways
Mastering Array Sort is essential for high-fidelity technical architecture and senior engineering roles in 2026.
JavaScript Array Sort
Sorting is one of the most common operations in real-world apps. However, JavaScript's default sorting behavior is often misunderstood by beginners.
1. Default Sorting (Alphabetical)
The
sort() method sorts an array alphabetically as strings. It mutates the original array.const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // ["Apple", "Banana", "Mango", "Orange"]2. Numeric Sort (Compare Function)
Because
sort() treats values as strings, numbers like "25" will be greater than "100" because "2" comes after "1". To sort numbers, you must provide a Compare Function.const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => a - b); // Ascending: [1, 5, 10, 25, 40, 100]3. Sorting Objects
Sorting lists of objects by a specific property is a daily task in frontend development.
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
cars.sort((a, b) => a.year - b.year);4. toSorted() (Modern 2026 Standard)
The modern alternative
toSorted() creates a new array instead of mutating the original. This is the preferred method in high-fidelity 2026 development.const sorted = points.toSorted((a, b) => a - b);[!CAUTION] Never usepoints.sort()on original state data (e.g., in React). Always usetoSorted()or copy the array first using[...points].sort()to avoid side effects.
Top Interview Questions
?Interview Question
Q:Why does [1, 10, 2].sort() result in [1, 10, 2]?
A:
Because sort() converts elements to strings before comparing. String '10' comes before '2'. You must provide a numeric compare function (a, b) => a - b.
?Interview Question
Q:How do you reverse an array without changing the original?
A:
Use the modern 'toReversed()' method, or copy it first: '[...arr].reverse()'.
?Interview Question
Q:What is Fisher-Yates shuffle?
A:
It is an efficient algorithm for shuffling an array randomly. While you can use sort(() => Math.random() - 0.5), it is not truly random and performs poorly compared to Fisher-Yates.
Course4All Engineering Team
Verified ExpertSenior Full-Stack Engineers & V8 Experts
Our JavaScript and engine-level content is developed by a collective of senior engineers focused on high-performance web architecture and 2026 standards.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.