Sorting & Searching Arrays
Sorting and searching are fundamental operations. JavaScript's sort() method has quirks you must understand — it sorts as strings by default! Learn proper number sorting, custom comparators, and efficient searching.
Sort & Search
- sort() — Sorts IN PLACE (mutates). Default: sorts as STRINGS ('10' < '9' because '1' < '9'!)
- Number sort — arr.sort((a, b) => a - b) for ascending, (a, b) => b - a for descending
- String sort — arr.sort((a, b) => a.localeCompare(b)) for proper alphabetical order
- reverse() — Reverses array in place
- flat() — Flattens nested arrays: [[1,2],[3,4]].flat() = [1,2,3,4]
- Array.from() — Create array from iterable: Array.from('hello') = ['h','e','l','l','o']
Sort & Search Code
// ⚠️ Default sort is alphabetical (STRING comparison)
const nums = [10, 9, 2, 20, 1, 100];
console.log([...nums].sort()); // [1, 10, 100, 2, 20, 9] ← WRONG!
// ✅ Proper number sort
console.log([...nums].sort((a, b) => a - b)); // [1, 2, 9, 10, 20, 100]
console.log([...nums].sort((a, b) => b - a)); // [100, 20, 10, 9, 2, 1]
// Sort objects
const users = [
{ name: "Charlie", age: 28 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
];
const byAge = [...users].sort((a, b) => a.age - b.age);
console.log(byAge.map(u => u.name)); // ["Alice", "Charlie", "Bob"]
const byName = [...users].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName.map(u => u.name)); // ["Alice", "Bob", "Charlie"]
// flat — flatten nested arrays
const nested = [[1, 2], [3, 4], [5, [6, 7]]];
console.log(nested.flat()); // [1, 2, 3, 4, 5, [6, 7]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6, 7]
console.log(nested.flat(Infinity)); // flatten all levels
// Array.from — create arrays
console.log(Array.from("hello")); // ["h", "e", "l", "l", "o"]
console.log(Array.from({length: 5}, (_, i) => i + 1)); // [1, 2, 3, 4, 5]Tip
Tip
Never sort the original array if you need it unchanged. Use [...arr].sort() to sort a copy. sort() mutates in place — one of the most surprising behaviors for developers coming from other languages.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Default sort() converts everything to strings: [10, 9, 2].sort() gives [10, 2, 9] because '10' < '2' alphabetically. ALWAYS provide a compare function for numbers: sort((a, b) => a - b).
Practice Task
Note
Sorting practice: (1) Sort an array of numbers ascending and descending. (2) Sort an array of user objects by name alphabetically using localeCompare. (3) Sort products by price, then by name for items with the same price.
Quick Quiz
Key Takeaways
- Sorting and searching are fundamental operations.
- sort() — Sorts IN PLACE (mutates). Default: sorts as STRINGS ('10' < '9' because '1' < '9'!)
- Number sort — arr.sort((a, b) => a - b) for ascending, (a, b) => b - a for descending
- String sort — arr.sort((a, b) => a.localeCompare(b)) for proper alphabetical order