Sorting and searching

Topic 4 of 4 in Arrays7 min readBeginnerFree course

Overview

sort() puts an array in order — but its default behaviour surprises everyone once:

JavaScript
[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 a should come first,
  • a positive number if b should come first,
  • 0 if they’re equal.

Default sort compares as text, so [10, 9, 1, 100] becomes [1, 10, 100, 9]. With (a, b) => a - b it becomes [1, 9, 10, 100]. A compare function returns negative to put a first, zero to keep the order, or positive to put b first.

JavaScript
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

JavaScript
const names = ['ravi', 'Asha', 'émile'];
names.sort();                             // ['Asha', 'ravi', 'émile'] — by character code
names.sort((a, b) => a.localeCompare(b)); // ['Asha', 'émile', 'ravi'] — human order

localeCompare understands upper and lower case, accents and the rules of different languages. It accepts options for things like numbers inside text:

JavaScript
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:

JavaScript
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 text

Breaking ties

To sort by one rule and then another, combine them with ||. If the first comparison gives 0 (a tie), the second decides:

JavaScript
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

JavaScript
events.sort((a, b) => a.date - b.date);         // Date objects subtract as numbers
tasks.sort((a, b) => Number(a.done) - Number(b.done)); // unfinished first

Keep the original

sort() and reverse() change the array. Use the copying versions when you need the original too:

JavaScript
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:

JavaScript
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 matches

Searching text

To find items that contain some text — like a search box — combine filter with includes, ignoring case:

JavaScript
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:

JavaScript
const byId = new Map(users.map((u) => [u.id, u]));
byId.get(42); // instant, however many users there are

You’ll meet Map properly in Maps and Sets.

Searching sorted data? For small arrays, find and includes are 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:

JavaScript
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;
}
Exercise

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.

JavaScript
function byLength(words) {
  // your code here
}

byLength(['pear', 'fig', 'apple', 'kiwi']); // ['fig', 'kiwi', 'pear', 'apple']

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 - b sorts numbers ascending; a.localeCompare(b) sorts text.
  • Combine rules with || to break ties.
  • toSorted() returns a sorted copy instead; use find, includes or a Map for searching.