JavaScript by Example

Array Search and Sort

find, some, every, flat, flatMap, and the numeric sort comparator that prevents string-order bugs.

Once you can create and transform arrays, the next common jobs are finding values, flattening nested lists, and sorting safely.

find returns the first matching element or undefined. some and every return booleans. All three stop as soon as the answer is known.

const users = [
  { id: 1, name: "Ana", admin: true },
  { id: 2, name: "Bo", admin: false },
  { id: 3, name: "Cal", admin: true },
];
 
console.log(users.find((u) => u.id === 1)?.name); // Ana
console.log(users.some((u) => u.admin));  // true
console.log(users.every((u) => u.admin)); // false

.sort() mutates the array and defaults to lexicographic string comparison, even for numbers. Spread first if you need the original array, and pass a numeric comparator for numbers.

const nums = [10, 9, 2, 100, 21];
 
console.log([...nums].sort());
// [10, 100, 2, 21, 9]
 
const sorted = [...nums].sort((a, b) => a - b);
console.log(sorted); // [2, 9, 10, 21, 100]
console.log(nums);   // original untouched

flat removes nested array levels. flatMap is equivalent to map followed by flat(1), which is useful when each item can expand into many items.

const matrix = [[1, 2], [3, 4], [5, 6]];
console.log(matrix.flat()); // [1, 2, 3, 4, 5, 6]
 
const sentences = ["hello world", "foo bar"];
const words = sentences.flatMap((s) => s.split(" "));
console.log(words); // ["hello", "world", "foo", "bar"]

In production

The default .sort() comparator converts values to strings first, so numeric data can look sorted in tests and fail in production. Always supply (a, b) => a - b for numbers. Always spread first when display order must not mutate source state.

Enjoyed this? Get more software craft delivered to your inbox.