Lesson 61 of 296
find, some, every, flat, flatMap and the sort trap
What you will learn
- Searching:
find,findIndex,findLast,includes - Testing:
someandevery - Flattening:
flatandflatMap - Sorting correctly, and the default sort trap
- Non-mutating versions:
toSortedandtoReversed
On this page
find and findIndex
const users = [
{ id: 1, name: "Sam" },
{ id: 2, name: "Ali" },
{ id: 3, name: "Sam" }
];
users.find((u) => u.name === "Sam"); { id: 1, name: "Sam" } (first match)
users.findIndex((u) => u.name === "Ali"); 1
users.find((u) => u.id === 99); undefined
users.findIndex((u) => u.id === 99); -1
users.findLast((u) => u.name === "Sam"); { id: 3, name: "Sam" }find stops at the first match, so it is faster than filter(...)[0].
includes vs some
includes(value)checks for an exact value (using same-value-zero, so it finds NaN).some(fn)checks with a condition.
[1, 2, 3].includes(2) true
users.some((u) => u.name === "Ali") truesome and every
| Method | Returns true when | Stops early when |
|---|---|---|
some | At least one item passes | It finds a passing item |
every | All items pass | It finds a failing item |
const ages = [22, 17, 30];
ages.some((a) => a < 18) true
ages.every((a) => a >= 18) falseEmpty array trap:
[].every((x) => x > 100) true
[].some((x) => x > 100) falseevery on an empty array is true (there is no item that fails). This can cause bugs, for example "all items are paid" being true for an empty basket. Check the length when it matters.
flat
flat flattens nested arrays.
[1, [2, 3], [4, [5]]].flat() [1, 2, 3, 4, [5]] (1 level by default)
[1, [2, [3, [4]]]].flat(2) [1, 2, 3, [4]]
[1, [2, [3, [4]]]].flat(Infinity) [1, 2, 3, 4]flatMap
flatMap is map followed by flat(1). Useful when each item turns into zero, one or many items.
const sentences = ["hello world", "good morning"];
sentences.flatMap((s) => s.split(" ")); ["hello", "world", "good", "morning"]It can also map and filter in one go, by returning an empty array to drop an item:
[1, 2, 3, 4].flatMap((n) => (n % 2 === 0 ? [n * 10] : [])) [20, 40]The sort trap
By default, sort() converts items to strings and sorts them alphabetically by character code.
[10, 1, 5, 100, 25].sort() [1, 10, 100, 25, 5]That is wrong for numbers: "10" comes before "5" as text.
Always give a compare function for numbers:
[10, 1, 5, 100, 25].sort((a, b) => a - b) [1, 5, 10, 25, 100] (smallest first)
[10, 1, 5, 100, 25].sort((a, b) => b - a) [100, 25, 10, 5, 1] (largest first)How the compare function works
sort calls your function with two items a and b:
| Your function returns | Result |
|---|---|
| A negative number | a goes before b |
| A positive number | b goes before a |
0 | Keep their order |
a - b is negative when a is smaller, so smaller numbers go first.
Sorting objects
const products = [
{ name: "Mug", pricePence: 499 },
{ name: "Kettle", pricePence: 2999 },
{ name: "Tea", pricePence: 299 }
];
products.sort((a, b) => a.pricePence - b.pricePence); by price
products.sort((a, b) => a.name.localeCompare(b.name)); by name, A to ZUse localeCompare for text. It handles capitals and accented letters properly.
Sort by two keys (status, then date):
items.sort((a, b) => a.status.localeCompare(b.status) || a.createdAt - b.createdAt);If the first comparison is 0 (a tie), || moves to the second one.
sort changes the original array
sort mutates the array and also returns it. This can cause bugs when the array is shared, for example React state or props.
const sorted = [...prices].sort((a, b) => a - b); copy first
const sorted2 = prices.toSorted((a, b) => a - b); ES2023, returns a new arrayreverse() also mutates; toReversed() does not.
Since ES2019, sort is stable: items that compare as equal keep their original order.
Common mistakes
sort()on numbers without a compare function.- Returning a boolean (
a > b) from the compare function. It does not work reliably; return a number. - Sorting shared data in place.
- Forgetting that
everyon an empty array is true. - Using
filter(...)[0]instead offind.
How to say it in an interview
"find returns the first matching element or undefined, and findIndex its index or minus one. some returns true if any element passes and every if all pass; both short-circuit, and every returns true for an empty array. flatMap maps and flattens one level. The classic trap is that sort without a comparator converts values to strings, so numbers sort wrongly; I always pass a comparator like a minus b, use localeCompare for strings, and since sort mutates, I copy first or use toSorted."
Key words
| Word | Meaning |
|---|---|
| find / findIndex | First matching item / its position |
| some / every | Whether any / all items pass a test |
| flat | Flattens nested arrays |
| flatMap | Map then flatten one level |
| Compare function | The function that tells sort the order of two items |
| Stable sort | Equal items keep their original order |
| toSorted | A sort that returns a new array |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.