Skip to content

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.

16 min read0/5 questions

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.

JavaScript
const steps = ["Preheat oven", "Mix", "Bake"]; // The index is the second argumentconsole.log(steps.map((step, i) => `${i + 1}. ${step}`)); // The array is the third: compare each value to its neighbourconst temps = [18, 21, 21, 19, 24];const rising = temps.filter((t, i, all) => i > 0 && t > all[i - 1]);console.log(rising); // The classic gotcha: parseInt takes (text, radix)console.log(["10", "10", "10"].map(parseInt));console.log(["10", "10", "10"].map((s) => parseInt(s, 10)));console.log(["10", "10", "10"].map(Number));
Output
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.

Predict the outputJavaScript

What does this print?

const result = ["7", "7", "7"].map(parseInt);
console.log(result.join(","));
Need a nudge? Hints walk you through it.

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.

JavaScript
const products = [ { id: "p1", name: "Desk lamp", price: 34, category: "home" }, { id: "p2", name: "Notebook", price: 6, category: "office" }, { id: "p3", name: "Plant pot", price: 12, category: "home" },]; // 1. Index by id: turn a list into a lookup objectconst byId = products.reduce((acc, p) => { acc[p.id] = p; return acc;}, {});console.log(byId.p3.name); // 2. Find the most expensive item in one passconst priciest = products.reduce((best, p) => (p.price > best.price ? p : best));console.log(priciest.name); // The same index, written without reduceconst byId2 = Object.fromEntries(products.map((p) => [p.id, p]));console.log(Object.keys(byId2));
Output
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.

find stops early, filter keeps going
4
0
9
1
15
2
22
3
30
4
goal = first value > 10

Order totals. We want the first total over 10.

1/5
QuestionMethodReturns when nothing matches
Which element is the first match?findundefined
Where is the first match?findIndex-1
Which is the last match?findLast / findLastIndexundefined / -1
Does any element match?somefalse
Do all elements match?everytrue (see below)
Is this exact value present?includesfalse

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.

Quick check
What does [].every((x) => x > 100) return?
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
const team = [ { name: "Sam", dept: "Design", age: 31 }, { name: "Ada", dept: "Eng", age: 36 }, { name: "Leo", dept: "Design", age: 24 }, { name: "Mia", dept: "Eng", age: 36 },]; // Department A to Z, then oldest first, then nameconst sorted = team.toSorted( (a, b) => a.dept.localeCompare(b.dept) || b.age - a.age || a.name.localeCompare(b.name));console.log(sorted.map((p) => `${p.dept} ${p.age} ${p.name}`)); // The mutation trap: two names for ONE arrayconst shown = team;shown.sort((a, b) => a.age - b.age);console.log(team[0].name); // team was reordered too
Output
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.

Put it in order3 steps

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.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

JavaScript
const orders = [ { id: 1, items: ["pen", "ink"] }, { id: 2, items: [] }, { id: 3, items: ["paper"] },]; console.log(orders.map((o) => o.items)); // nestedconsole.log(orders.flatMap((o) => o.items)); // one flat list console.log([1, [2, [3, [4]]]].flat()); // one levelconsole.log([1, [2, [3, [4]]]].flat(Infinity)); // all levels // Map and filter in one pass: [] drops an item, [x] keeps itconst input = ["4", "x", "15", "", "8"];const numbers = input.flatMap((s) => (s.trim() && !Number.isNaN(Number(s)) ? [Number(s)] : []));console.log(numbers);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

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);
Need a nudge? Hints walk you through it.

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 find or some does not express.
  • You produce several results in one pass, such as a total, a count and a list of errors.
  • You need to await inside, one item at a time. map with 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 the pairs0/5 matched

Match each method to what it returns.

Choose an item, then its match on the other side.
Key terms
callback arguments
Iteration methods call your function with (element, index, array).
short-circuit
Stopping as soon as the answer is known. find, some and every do; filter and map do not.
vacuous truth
Why [].every(fn) is true: with no elements, none can fail.
stable sort
Items that compare equal keep their original order. Guaranteed in JavaScript since ES2019.
flatMap
map then flat() one level. Return [] to drop an item or several items to expand it.
mutation
Changing an array in place. sort, reverse, push and splice mutate; toSorted and toReversed do not.