Sorting and searching
Overview
sort() puts an array in order — but its default behaviour surprises everyone once:
[10, 9, 1, 100].sort(); // [1, 10, 100, 9] — compared as text!Without instructions, sort converts every item to a string and compares the strings character by character. As text, '10' comes before '9' because '1' comes before '9' — just as “apple” comes before “banana”. It works for simple words, but almost never for numbers or objects.
Compare functions
Pass a function that receives two items and returns:
- a negative number if
ashould come first, - a positive number if
bshould come first, - 0 if they’re equal.
const nums = [10, 9, 1, 100];
nums.sort((a, b) => a - b); // [1, 9, 10, 100]
nums.sort((a, b) => b - a); // [100, 10, 9, 1]Why does a - b work? If a is smaller, a - b is negative, so a goes first — ascending order. Swap to b - a and everything flips.
sort calls your function many times with different pairs; you never need to know which pairs, only how to compare any two.
Sorting text
const names = ['ravi', 'Asha', 'émile'];
names.sort(); // ['Asha', 'ravi', 'émile'] — by character code
names.sort((a, b) => a.localeCompare(b)); // ['Asha', 'émile', 'ravi'] — human orderlocaleCompare understands upper and lower case, accents and the rules of different languages. It accepts options for things like numbers inside text:
const files = ['file10', 'file2', 'file1'];
files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
// ['file1', 'file2', 'file10']Sorting objects
Compare a property of each object:
const lessons = [
{ title: 'Closures', minutes: 9 },
{ title: 'Arrays', minutes: 6 },
{ title: 'Loops', minutes: 6 },
];
lessons.sort((a, b) => a.minutes - b.minutes); // by number
lessons.sort((a, b) => a.title.localeCompare(b.title)); // by textBreaking ties
To sort by one rule and then another, combine them with ||. If the first comparison gives 0 (a tie), the second decides:
lessons.sort(
(a, b) => a.minutes - b.minutes || a.title.localeCompare(b.title),
);
// Arrays (6), Loops (6), Closures (9)JavaScript’s sort is stable: items that compare as equal keep their original order. So you can also sort by the secondary key first, then by the primary key.
Dates and booleans
events.sort((a, b) => a.date - b.date); // Date objects subtract as numbers
tasks.sort((a, b) => Number(a.done) - Number(b.done)); // unfinished firstKeep the original
sort() and reverse() change the array. Use the copying versions when you need the original too:
const sorted = nums.toSorted((a, b) => a - b);
const backwards = nums.toReversed();Before toSorted existed (2023), the usual pattern was to copy first: [...nums].sort((a, b) => a - b). You’ll see both.
Sorting in place surprises people. If a function sorts an array it was given, the caller’s array is reordered too. Return a sorted copy unless you really mean to change it.
Searching
For most arrays, the built-in methods are all you need:
nums.includes(9); // true / false
nums.indexOf(9); // position or -1
lessons.find((l) => l.title === 'Loops'); // the item or undefined
lessons.filter((l) => l.minutes === 6); // all matchesSearching text
To find items that contain some text — like a search box — combine filter with includes, ignoring case:
function search(list, query) {
const q = query.trim().toLowerCase();
return list.filter((l) => l.title.toLowerCase().includes(q));
}
search(lessons, 'LOO'); // [{ title: 'Loops', … }]Faster lookups
find checks items one by one. If you look things up by the same key again and again — say, users by ID — build a Map once and look up directly:
const byId = new Map(users.map((u) => [u.id, u]));
byId.get(42); // instant, however many users there areYou’ll meet Map properly in Maps and Sets.
Searching sorted data? For small arrays,
findandincludesare plenty fast. Reach for smarter algorithms such as binary search only when lists get very large.
Random order
A tempting shortcut, arr.sort(() => Math.random() - 0.5), does not shuffle fairly. Use the Fisher–Yates shuffle instead:
function shuffle(list) {
const copy = [...list];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}Sort by length
Return a new array of words sorted from shortest to longest, leaving the original unchanged. Words of the same length should be in alphabetical order.
function byLength(words) {
// your code here
}
byLength(['pear', 'fig', 'apple', 'kiwi']); // ['fig', 'kiwi', 'pear', 'apple']function byLength(words) {
return words.toSorted(
(a, b) => a.length - b.length || a.localeCompare(b),
);
}Summary
sort()changes the array and compares items as strings by default.- Pass a compare function: return negative (a first), zero, or positive (b first).
a - bsorts numbers ascending;a.localeCompare(b)sorts text.- Combine rules with
||to break ties. toSorted()returns a sorted copy instead; usefind,includesor aMapfor searching.