Array Methods: Map, Filter and Reduce

Updated · 9 min read
mediumES2026javascriptarraysmapfilterreducefunctionalinterview

map, filter and reduce are array methods that process every item through a function you provide, and return a new result without changing the original array. map transforms each item, filter selects some items, and reduce combines all items into one value. Together they replace most loops that build new data, and they read like a description of what you want: "the names of the unpaid students", "the total of the large payments".

In One Minute

  • map(fn) returns a new array of the same length, each item replaced by fn(item).
  • filter(fn) returns a new array with only the items for which fn returns truthy.
  • reduce(fn, start) walks the array carrying an accumulator and returns one final value. Always pass start.
  • forEach(fn) runs fn on each item for its side effects and returns undefined.
  • flat() flattens nested arrays; flatMap(fn) maps then flattens one level.
  • Chain them into pipelines: list.filter(...).map(...).reduce(...).

The Callback

Each method takes a callback function that it calls once per item, with three arguments:

syntax.js
array.map((item, index, array) => newValue)
array.filter((item, index, array) => keep)
array.reduce((accumulator, item, index, array) => nextAccumulator, initialValue)

You usually need only the first argument (or the first two for reduce).

map: Transform Every Item

map calls your function on every item and collects the results into a new array of the same length.

map.js▶ Try it
const pricesInDollars = [120, 85.5, 45];
 
const cents = pricesInDollars.map((p) => Math.round(p * 100));
console.log(cents);
 
const labels = pricesInDollars.map((p, i) => `${i + 1}. $${p.toFixed(2)}`);
console.log(labels);
 
console.log(pricesInDollars);
Output
[12000, 8550, 4500]
['1. $120.00', '2. $85.50', '3. $45.00']
[120, 85.5, 45]

The original array is unchanged. map is the right tool whenever the output has one item per input item: converting units, picking a property, formatting labels.

map-objects.js▶ Try it
const students = [
  { first: "Navika", last: "Anamaneni", grade: 9 },
  { first: "Advitha", last: "Anamaneni", grade: 11 },
];
 
console.log(students.map((s) => s.first));
console.log(students.map((s) => ({ name: `${s.first} ${s.last}`, grade: s.grade })));
Output
['Navika', 'Advitha']
[{ name: 'Navika Anamaneni', grade: 9 }, { name: 'Advitha Anamaneni', grade: 11 }]

filter: Keep Some Items

filter keeps the items for which your function returns a truthy value:

filter.js▶ Try it
const payments = [
  { name: "Navika", amount: 120, paid: true },
  { name: "Srihitha", amount: 85, paid: false },
  { name: "Advitha", amount: 45, paid: false },
];
 
const unpaid = payments.filter((p) => !p.paid);
console.log(unpaid.map((p) => p.name));
 
console.log(payments.filter((p) => p.amount > 500));
console.log([0, 1, "", "a", null, 2].filter(Boolean));
Output
['Srihitha', 'Advitha']
[]
[1, 'a', 2]

filter always returns an array, empty when nothing matches. When you want only the first match, use find instead, which stops searching early. filter(Boolean) is a common idiom to drop every falsy value.

reduce: Combine into One Value

reduce walks the array and carries an accumulator: a running result that your function updates for each item. The second argument to reduce is the accumulator's starting value.

reduce.js▶ Try it
const fees = [120, 85, 45];
 
const total = fees.reduce((sum, fee) => sum + fee, 0);
console.log(total);
 
const steps = [];
fees.reduce((sum, fee) => {
  steps.push(`${sum} + ${fee} = ${sum + fee}`);
  return sum + fee;
}, 0);
console.log(steps);
Output
250
['0 + 120 = 120', '120 + 85 = 205', '205 + 45 = 250']

Explanation: the accumulator starts at 0. For each fee, the callback returns the new sum, which becomes the accumulator for the next fee. The value returned for the last item is the result.

The accumulator can be anything: a number, a string, an object, an array. Grouping into an object is a classic use:

reduce-group.js▶ Try it
const payments = [
  { grade: 9, amount: 120 },
  { grade: 11, amount: 85 },
  { grade: 9, amount: 60 },
];
 
const totalsByGrade = payments.reduce((totals, p) => {
  totals[p.grade] = (totals[p.grade] ?? 0) + p.amount;
  return totals;
}, {});
console.log(totalsByGrade);
Output
{ 9: 180, 11: 85 }

For grouping specifically, ES2024 added Object.groupBy, which is clearer than a hand-written reduce; the looping over objects lesson covers it. For summing numbers, a reduce is fine.

forEach: Do Something with Each Item

forEach runs a function for each item and returns undefined. Use it for side effects such as printing or updating the page, not for building new arrays:

for-each.js▶ Try it
const names = ["Navika", "Srihitha"];
names.forEach((name, i) => console.log(`${i + 1}: ${name}`));
 
const result = names.forEach((n) => n.toUpperCase());
console.log(result);
Output
1: Navika
2: Srihitha
undefined

forEach can't be stopped early (no break), and it doesn't wait for async callbacks. A for...of loop is often the better choice; the async chapter shows why.

flat and flatMap

flat(depth) flattens nested arrays into one; flatMap(fn) maps each item to an array and flattens the results by one level:

flat.js▶ Try it
const byTerm = [[120, 85], [45], [200, 30]];
console.log(byTerm.flat());
console.log([1, [2, [3, [4]]]].flat(Infinity));
 
const students = [
  { name: "Navika", payments: [120, 60] },
  { name: "Advitha", payments: [45] },
];
console.log(students.flatMap((s) => s.payments));
console.log(students.flatMap((s) => s.payments.map((amount) => `${s.name}: ${amount}`)));
Output
[120, 85, 45, 200, 30]
[1, 2, 3, 4]
[120, 60, 45]
['Navika: 120', 'Navika: 60', 'Advitha: 45']

flatMap is also a "map and filter in one pass" trick: return [] to drop an item and [value] to keep it.

Chaining into Pipelines

Because map and filter return arrays, calls can be chained. Each step does one simple thing:

pipeline.js▶ Try it
const payments = [
  { name: "Navika", amount: 120, paid: true },
  { name: "Srihitha", amount: 85, paid: false },
  { name: "Advitha", amount: 450, paid: false },
  { name: "Zoe", amount: 30, paid: false },
];
 
const bigUnpaidTotal = payments
  .filter((p) => !p.paid)
  .filter((p) => p.amount >= 50)
  .map((p) => p.amount)
  .reduce((sum, a) => sum + a, 0);
 
console.log(bigUnpaidTotal);
Output
535

Read it top to bottom: unpaid payments, at least $50, their amounts, added up. Each intermediate array is short-lived; for ordinary data sizes the clarity is worth far more than the extra arrays.

In Practice

The Fee Tracker's dashboard turns raw payments into a summary per student: total paid, number of payments, and largest single payment, sorted by total:

dashboard.js▶ Try it
const payments = [
  { name: "Navika", amount: 120 },
  { name: "Advitha", amount: 45 },
  { name: "Navika", amount: 60 },
  { name: "Srihitha", amount: 85 },
  { name: "Advitha", amount: 200 },
];
 
const summary = Object.entries(
  payments.reduce((acc, p) => {
    (acc[p.name] ??= []).push(p.amount);
    return acc;
  }, {})
)
  .map(([name, amounts]) => ({
    name,
    total: amounts.reduce((s, a) => s + a, 0),
    count: amounts.length,
    largest: Math.max(...amounts),
  }))
  .toSorted((a, b) => b.total - a.total);
 
summary.forEach((s) => console.log(`${s.name}: $${s.total} in ${s.count} (largest $${s.largest})`));
Output
Advitha: $245 in 2 (largest $200)
Navika: $180 in 2 (largest $120)
Srihitha: $85 in 1 (largest $85)

Common Mistakes

Using map for side effects. list.map((x) => console.log(x)) builds a useless array of undefined. Use forEach or for...of.

Forgetting to return in a callback with braces. list.map((x) => { x * 2 }) gives [undefined, ...].

Calling reduce without an initial value. Wrong types and crashes on empty arrays.

Passing a function that takes extra parameters. ["1", "2", "3"].map(parseInt) gives [1, NaN, NaN], because map passes the index as parseInt's second argument (the radix). Write .map((s) => parseInt(s, 10)) or .map(Number).

Under the Hood

Each method in a chain loops over its input fully and allocates a new array before the next one starts, so filter().map().reduce() walks the data three times. For arrays of a few thousand items this costs microseconds. When it does matter (millions of items, hot code), the options are a single for...of loop, or iterator helpers (ES2025), which process items lazily one at a time without intermediate arrays: list.values().filter(fn).map(fn).toArray(). They have their own lesson in the iterators chapter.

Interview Corner

What is the difference between map and forEach?

map returns a new array of the callback's return values, with the same length as the input. forEach returns undefined and is used only for side effects. Neither can be stopped early with break.

Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?

map calls the callback with (item, index, array). parseInt takes (string, radix), so it receives radix 0 (treated as 10), then 1 (invalid, so NaN), then 2 ("3" isn't a binary digit, so NaN). Use .map(Number) or an arrow that passes only the string.

Implement map using reduce.

const map = (arr, fn) => arr.reduce((out, x, i) => { out.push(fn(x, i, arr)); return out; }, []);. reduce is the most general of the three: filter and map can both be written with it, but the dedicated methods are clearer.

Practice

Challenge: From the list below, produce an array of strings like "SRIHITHA owes $85" for every student with a balance above zero, sorted by balance from largest to smallest.

Show solution
owes.js▶ Try it
const students = [
  { name: "Navika", balance: 0 },
  { name: "Srihitha", balance: 85 },
  { name: "Advitha", balance: 450 },
];
 
const lines = students
  .filter((s) => s.balance > 0)
  .toSorted((a, b) => b.balance - a.balance)
  .map((s) => `${s.name.toUpperCase()} owes $${s.balance}`);
 
console.log(lines);
Output
['ADVITHA owes $450', 'SRIHITHA owes $85']

Quick check: map, filter and reduce

3 questions
1What does [1, 2, 3].map((n) => n * 2) return?
2What does filter return when nothing matches?
3What happens when you call reduce on an empty array without an initial value?

Key Takeaways

MethodReturnsLength of resultTypical use
mapNew arraySame as inputTransform each item
filterNew arraySame or shorterSelect items
reduceAny valueOne valueSum, group, count
forEachundefinedn/aSide effects
flatMapNew arrayAnyMap to several items each

Was this tutorial helpful?

Lesson 35 of 139