Lesson 7 of 50JavaScript basics
Array Methods in Depth
Go past the basics of map, filter and reduce with callback arguments, searching, safe sorting, flat and flatMap, chaining, and knowing when a plain loop is clearer.
The arrays and objects lesson introduced map, filter, reduce, find and the sort trap. That is enough to get started, but real code throws harder questions at you. Why does ["1", "2", "3"].map(parseInt) return nonsense? Why did sorting a list in one component reorder it in another? When is a chain of five methods worse than a loop? This lesson goes a level deeper: how the callbacks are called, how to search efficiently, how to sort by several fields without mutating anything, how to flatten nested data, and how to choose between methods and loops.
What the callback receives
Every iteration method (map, filter, forEach, find, some, every and friends) calls your function with three arguments, not one: the current element, its index, and the whole array. You usually only name the first, but the others are there when you need them.
Press Run (⌘ Enter) to see what happens.The parseInt result is the famous one. map calls parseInt("10", 0), then parseInt("10", 1), then parseInt("10", 2), because it passes the index as the second argument. parseInt reads its second argument as the radix (the number base): 0 means "work it out" (base 10), 1 is not a valid base so you get NaN, and "10" in base 2 is 2. The fix is to wrap the call in an arrow function so you control exactly which arguments are passed, or to use Number, which only looks at its first argument.
The lesson: passing a function you did not write straight into map is risky unless you know every parameter it accepts.
What does this print?
const result = ["7", "7", "7"].map(parseInt);
console.log(result.join(","));forEach is not map
forEach runs a function for each element and returns undefined. Use it for side effects, like logging or updating something outside the array. If you are building a new array, use map: writing const names = users.forEach(...) always gives you undefined. Also, you cannot stop a forEach early: break is a syntax error inside it, and return only ends the current callback.
reduce beyond sums
reduce folds an array into one value, and that value can be anything: a number, a string, an object, a Map. Two shapes appear constantly in real code.
Press Run (⌘ Enter) to see what happens.Notice the return acc in the first reducer. Forgetting it is the most common reduce bug: the next step receives undefined as the accumulator and the code crashes with "cannot set properties of undefined". The second example leaves out the starting value on purpose, so the first product becomes the starting "best". That only works because the array is never empty; on an empty array, reduce without a start throws.
reduce is powerful, but it is also the method most likely to make code hard to read. If a reducer needs more than a few lines, or if you have to think hard to work out what the accumulator holds, a for...of loop or Object.fromEntries is usually kinder to the next reader.
Searching: stop as soon as you know
filter always visits every element. When you only need the first match, or a yes or no answer, use a method that short-circuits, meaning it stops the moment it has its answer.
Order totals. We want the first total over 10.
| Question | Method | Returns when nothing matches |
|---|---|---|
| Which element is the first match? | find | undefined |
| Where is the first match? | findIndex | -1 |
| Which is the last match? | findLast / findLastIndex | undefined / -1 |
| Does any element match? | some | false |
| Do all elements match? | every | true (see below) |
| Is this exact value present? | includes | false |
every on an empty array returns true: there is no element that fails, so "all of them pass" is technically correct. Mathematicians call this vacuous truth. It bites in code like "enable the Submit button if every field is valid", which is then enabled when the form has no fields at all. Check the length too if that matters.
includes is also better than indexOf for a yes or no check, because indexOf cannot find NaN (it uses ===, and NaN === NaN is false) while includes can.
[].every((x) => x > 100) return?Sorting without surprises
You already know to pass a comparator, (a, b) => a - b, and that sort mutates the array. Two more things make sorting reliable in real apps.
Sort by several fields. Compare by the first field; only if that is a tie, fall back to the next. The || operator does this neatly, because a tie returns 0, which is falsy.
Sort is stable. Since ES2019, items that compare equal keep their original order. That means sorting by surname and then by city gives you people grouped by city, still alphabetical by surname inside each city.
Press Run (⌘ Enter) to see what happens.The last three lines are the bug that bites React developers. shown and team point to the same array, so sorting one reorders the other. In React that means you changed state behind the framework's back. Use toSorted (ES2023, in all modern browsers and Node 20+) or copy first with [...team].sort(...). The same goes for reverse, which mutates; toReversed does not.
A shop sorts products: in-stock items first, then cheapest first, then by name. Put the comparator's checks in the order they must run.
- Tap the steps below in the right order.
flat and flatMap
Data often arrives nested: orders that each contain a list of items, posts that each have tags. flat() removes one level of nesting (pass a number for more levels, or Infinity for all). flatMap(fn) is map followed by flat(), and it has a neat trick: return an array to output several items, or an empty array to output none. That lets one call filter and transform at the same time.
Press Run (⌘ Enter) to see what happens.What does this print?
const posts = [{ tags: ["js", "css"] }, { tags: ["js"] }];
const tags = posts.flatMap((p) => p.tags);
console.log(tags.length, new Set(tags).size);Chaining, and when a loop is clearer
Because map, filter, flatMap and toSorted all return new arrays, you can chain them. A chain reads like a recipe: keep the active users, take their emails, sort them. Put each step on its own line, and give the callbacks clear parameter names (user, not x).
Chains have costs, though. Each step builds a whole new array, so a five-step chain walks the data five times. For a few hundred items that is irrelevant; for a million, or in a hot animation loop, it can matter. More often the cost is readability. A plain for...of loop is the clearer choice when:
- You need to stop early in a way
findorsomedoes not express. - You produce several results in one pass, such as a total, a count and a list of errors.
- You need to
awaitinside, one item at a time.mapwith an async callback starts everything at once and gives you an array of promises (the async lessons explain why). - The logic has several branches, so the callback would be a dozen lines.
Good code mixes both. Use methods for the clean, single-purpose transformations, and a loop when the work is genuinely step by step.
Match each method to what it returns.
- callback arguments
- Iteration methods call your function with
(element, index, array). - short-circuit
- Stopping as soon as the answer is known.
find,someandeverydo;filterandmapdo not. - vacuous truth
- Why
[].every(fn)istrue: with no elements, none can fail. - stable sort
- Items that compare equal keep their original order. Guaranteed in JavaScript since ES2019.
- flatMap
mapthenflat()one level. Return[]to drop an item or several items to expand it.- mutation
- Changing an array in place.
sort,reverse,pushandsplicemutate;toSortedandtoReverseddo not.