JavaScript map, filter and reduce (plus find, some, every) Explained

map, filter and reduce are the three array methods you will use most once you start working with real data: transforming API responses, picking failed tests, totalling prices, grouping results by status. They replace most hand-written loops with short, readable code. In this lesson you will learn exactly what each one does, how to chain them, the related search methods find, some and every, the new Object.groupBy, and the mistakes that trip up beginners.

Advertisement

📖 What You’ll Learn: map to transform every item, filter to keep matching items, reduce to combine items into one value, the callback arguments, find, findLast, findIndex, some and every, chaining methods into pipelines, grouping with reduce and Object.groupBy, when to use a loop instead, and common mistakes such as forgetting to return.


🗺️ map: Transform Every Item

Definition: arr.map(callback) calls the callback for every item and returns a new array of the same length containing whatever the callback returned. The original array is not changed.

📄 map.js

const prices = [100, 250, 80];
const withTax = prices.map((p) => p * 1.18);
console.log(withTax, prices);

const users = [
  { first: "Asha", last: "Rao", role: "tester" },
  { first: "Ravi", last: "Kumar", role: "dev" },
];
console.log(users.map((u) => `${u.first} ${u.last}`));
console.log(users.map((u) => ({ name: u.first, isTester: u.role === "tester" })));
console.log(["a", "b"].map((item, index) => `${index}:${item}`));

⌨️ Terminal

node map.js

🖥️ Output

[ 118, 295, 94.39999999999999 ] [ 100, 250, 80 ]
[ 'Asha Rao', 'Ravi Kumar' ]
[ { name: 'Asha', isTester: true }, { name: 'Ravi', isTester: false } ]
[ '0:a', '1:b' ]

The callback receives three arguments: (item, index, array). Most of the time you only need the item.

⚠️ Watch out: Use map only when you need the new array. If you just want to do something for each item (log it, click it), use forEach or for...of. A map whose result is ignored confuses readers.


🔎 filter: Keep Matching Items

Definition: arr.filter(callback) returns a new array with only the items for which the callback returned a truthy value. The result can be shorter, or empty.

📄 filter.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "search", status: "failed", ms: 1430 },
  { test: "cart", status: "passed", ms: 2610 },
  { test: "refund", status: "skipped", ms: 0 },
];

const failed = results.filter((r) => r.status === "failed");
const slow = results.filter((r) => r.ms > 2000);
const ran = results.filter((r) => r.status !== "skipped");

console.log(failed.map((r) => r.test));
console.log(slow.map((r) => r.test));
console.log(ran.length, "of", results.length, "ran");

console.log([0, "", "QA", null, 7, undefined].filter(Boolean));   // remove falsy values

⌨️ Terminal

node filter.js

🖥️ Output

[ 'search' ]
[ 'cart' ]
3 of 4 ran
[ 'QA', 7 ]

filter(Boolean) is a handy idiom: Boolean is a function that returns false for falsy values, so they are removed.


🧮 reduce: Combine Items into One Value

Definition: arr.reduce(callback, initialValue) walks through the array and builds up a single result, called the accumulator. The callback receives (accumulator, item, index, array) and returns the new accumulator.

📄 reduce.js

const cart = [
  { item: "Pen", price: 10, qty: 3 },
  { item: "Notebook", price: 45, qty: 2 },
  { item: "Lamp", price: 899, qty: 1 },
];

const total = cart.reduce((sum, line) => sum + line.price * line.qty, 0);
console.log("total:", total);

const itemCount = cart.reduce((count, line) => count + line.qty, 0);
console.log("items:", itemCount);

const mostExpensive = cart.reduce((best, line) => (line.price > best.price ? line : best));
console.log("most expensive:", mostExpensive.item);

⌨️ Terminal

node reduce.js

🖥️ Output

total: 1019
items: 6
most expensive: Lamp

Step by step for the total: the accumulator starts at 0, then becomes 0 + 30 = 30, then 30 + 90 = 120, then 120 + 899 = 1019.

⚠️ Watch out: Always pass an initial value (the 0 above) unless you are sure the array is never empty. [].reduce((a, b) => a + b) throws TypeError: Reduce of empty array with no initial value.

📄 reduce-empty.js

const noResults = [];
console.log(noResults.reduce((sum, n) => sum + n, 0));   // safe: 0
console.log(noResults.reduce((sum, n) => sum + n));      // throws

⌨️ Terminal

node reduce-empty.js

🖥️ Output

0
/home/you/js-course/reduce-empty.js:3
console.log(noResults.reduce((sum, n) => sum + n));      // throws
                      ^

TypeError: Reduce of empty array with no initial value
    at Array.reduce (<anonymous>)
    at Object.<anonymous> (/home/you/js-course/reduce-empty.js:3:23)

Node.js v26.13.0

reduce can build any shape of result, such as an object that counts occurrences:

📄 count.js

const statuses = ["passed", "failed", "passed", "skipped", "passed"];
const counts = statuses.reduce((acc, s) => {
  acc[s] = (acc[s] ?? 0) + 1;
  return acc;
}, {});
console.log(counts);

⌨️ Terminal

node count.js

🖥️ Output

{ passed: 3, failed: 1, skipped: 1 }

Advertisement

🎯 find, findLast, findIndex, some and every

These methods search with a callback and stop early once the answer is known:

MethodReturnsIf nothing matches
find(fn)First matching itemundefined
findLast(fn)Last matching item (ES2023)undefined
findIndex(fn) / findLastIndex(fn)Index of the match-1
some(fn)true if at least one item matchesfalse
every(fn)true if all items matchtrue for an empty array

📄 search.js

const runs = [
  { id: 1, status: "passed", ms: 900 },
  { id: 2, status: "failed", ms: 1500 },
  { id: 3, status: "failed", ms: 700 },
];

console.log(runs.find((r) => r.status === "failed")?.id);
console.log(runs.findLast((r) => r.status === "failed")?.id);
console.log(runs.findIndex((r) => r.ms > 1000));
console.log(runs.find((r) => r.status === "skipped"));
console.log(runs.some((r) => r.status === "failed"));
console.log(runs.every((r) => r.ms < 2000));
console.log([].every((r) => r.ok), [].some((r) => r.ok));   // empty-array results

⌨️ Terminal

node search.js

🖥️ Output

2
3
1
undefined
true
true
true false

💡 Tip: [].every(...) is true (“no item breaks the rule”). A test that asserts “every row is valid” passes on an empty table, so also assert the table is not empty.


⛓️ Chaining Methods into a Pipeline

Because map and filter return arrays, you can chain them. Read the chain from top to bottom like a recipe:

📄 chain.js

const orders = [
  { id: 101, customer: "Asha", total: 1299, status: "delivered" },
  { id: 102, customer: "Ravi", total: 349, status: "cancelled" },
  { id: 103, customer: "Meera", total: 2499, status: "delivered" },
  { id: 104, customer: "Asha", total: 899, status: "delivered" },
];

const asha = orders
  .filter((o) => o.status === "delivered")
  .filter((o) => o.customer === "Asha")
  .map((o) => o.total)
  .reduce((sum, t) => sum + t, 0);

console.log("Asha delivered total:", asha);

const report = orders
  .filter((o) => o.total > 500)
  .toSorted((a, b) => b.total - a.total)
  .map((o) => `#${o.id} ${o.customer.padEnd(6)} ₹${o.total}`)
  .join("\n");
console.log(report);

⌨️ Terminal

node chain.js

🖥️ Output

Asha delivered total: 2198
#103 Meera  ₹2499
#101 Asha   ₹1299
#104 Asha   ₹899

💡 Tip: Put filter before map where possible, so later steps process fewer items. Give long chains intermediate variables if they stop being readable.


Advertisement

🗂️ Grouping: reduce and Object.groupBy

Grouping items by a key, such as test results by status, is a very common task. ES2024 added Object.groupBy(array, fn), which does it in one call (Node.js 21+):

📄 group.js

const results = [
  { test: "login", status: "passed" },
  { test: "search", status: "failed" },
  { test: "cart", status: "passed" },
  { test: "refund", status: "skipped" },
];

const grouped = Object.groupBy(results, (r) => r.status);
console.log(Object.keys(grouped));
console.log(grouped.passed.map((r) => r.test));

// The same with reduce (works in older environments)
const grouped2 = results.reduce((acc, r) => {
  (acc[r.status] ??= []).push(r.test);
  return acc;
}, {});
console.log(grouped2);

⌨️ Terminal

node group.js

🖥️ Output

[ 'passed', 'failed', 'skipped' ]
[ 'login', 'cart' ]
{
  passed: [ 'login', 'cart' ],
  failed: [ 'search' ],
  skipped: [ 'refund' ]
}

Map.groupBy works the same way but returns a Map, which allows keys that are not strings.


⚠️ Common Mistakes

Forgetting to return in a block body

📄 no-return.js

const prices = [10, 20];
console.log(prices.map((p) => { p * 2; }));      // block without return
console.log(prices.map((p) => p * 2));          // expression body returns

⌨️ Terminal

node no-return.js

🖥️ Output

[ undefined, undefined ]
[ 20, 40 ]

Using map for side effects or filter to change items

filter decides which items to keep; it does not change them. Returning a modified item from a filter callback just counts as “truthy”. Use map to change items.

Mutating objects inside map

📄 mutate-in-map.js

const users = [{ name: "asha" }];
const upper = users.map((u) => { u.name = u.name.toUpperCase(); return u; });   // changes the original!
console.log(users[0].name);

const users2 = [{ name: "asha" }];
const upper2 = users2.map((u) => ({ ...u, name: u.name.toUpperCase() }));       // new objects
console.log(users2[0].name, upper2[0].name);

⌨️ Terminal

node mutate-in-map.js

🖥️ Output

ASHA
asha ASHA

async callbacks

arr.map(async (x) => ...) returns an array of promises, not results, and forEach ignores them completely. You will learn to combine them with Promise.all in Module 10.


🧪 Tester Scenario: Summarise a Test Report

This example turns raw results (the kind a JSON reporter produces) into a summary using only the methods from this lesson:

📄 summary.js

const report = [
  { suite: "auth", test: "login valid", status: "passed", ms: 820 },
  { suite: "auth", test: "login invalid", status: "passed", ms: 610 },
  { suite: "cart", test: "add item", status: "failed", ms: 1430, error: "Timeout 5000ms" },
  { suite: "cart", test: "remove item", status: "passed", ms: 540 },
  { suite: "pay", test: "card", status: "failed", ms: 2210, error: "Expected 200, got 500" },
  { suite: "pay", test: "upi", status: "skipped", ms: 0 },
];

const executed = report.filter((r) => r.status !== "skipped");
const passed = executed.filter((r) => r.status === "passed").length;
const durationMs = report.reduce((sum, r) => sum + r.ms, 0);
const passRate = ((passed / executed.length) * 100).toFixed(1);

console.log(`Executed ${executed.length}/${report.length}, passed ${passed}, pass rate ${passRate}%, total ${(durationMs / 1000).toFixed(1)}s`);
console.log("all suites have a test:", ["auth", "cart", "pay"].every((s) => report.some((r) => r.suite === s)));

const failuresBySuite = Object.groupBy(report.filter((r) => r.status === "failed"), (r) => r.suite);
for (const [suite, tests] of Object.entries(failuresBySuite)) {
  console.log(`${suite}: ${tests.map((t) => `${t.test} (${t.error})`).join("; ")}`);
}
console.log("slowest:", report.reduce((a, b) => (b.ms > a.ms ? b : a)).test);

⌨️ Terminal

node summary.js

🖥️ Output

Executed 5/6, passed 3, pass rate 60.0%, total 5.6s
all suites have a test: true
cart: add item (Timeout 5000ms)
pay: card (Expected 200, got 500)
slowest: card

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Use map to convert ["login", "search", "cart"] into ["LOGIN.spec.js", "SEARCH.spec.js", "CART.spec.js"].

Show answer

📄 practice1.js

const names = ["login", "search", "cart"];
console.log(names.map((n) => `${n.toUpperCase()}.spec.js`));

🖥️ Output

[ 'LOGIN.spec.js', 'SEARCH.spec.js', 'CART.spec.js' ]

Q2. Use filter to keep only valid emails (containing @ and a dot after it) from ["a@b.com", "bad", "x@y", "qa@sqatools.in"].

Show answer

📄 practice2.js

const emails = ["a@b.com", "bad", "x@y", "qa@sqatools.in"];
const valid = emails.filter((e) => e.includes("@") && e.slice(e.indexOf("@")).includes("."));
console.log(valid);

🖥️ Output

[ 'a@b.com', 'qa@sqatools.in' ]

Q3. Use reduce to find the average of [320, 410, 1290, 250, 730] response times.

Show answer

📄 practice3.js

const times = [320, 410, 1290, 250, 730];
const avg = times.reduce((sum, t) => sum + t, 0) / times.length;
console.log(avg);

🖥️ Output

600

Q4. Check with some whether any product is out of stock, and with every whether all prices are positive, for [{ p: 10, stock: 5 }, { p: 25, stock: 0 }].

Show answer

📄 practice4.js

const products = [{ p: 10, stock: 5 }, { p: 25, stock: 0 }];
console.log(products.some((x) => x.stock === 0), products.every((x) => x.p > 0));

🖥️ Output

true true

Q5. Use reduce to turn [["env", "qa"], ["browser", "firefox"]] into the object { env: "qa", browser: "firefox" }. Then do the same with Object.fromEntries.

Show answer

📄 practice5.js

const pairs = [["env", "qa"], ["browser", "firefox"]];
const viaReduce = pairs.reduce((obj, [k, v]) => ({ ...obj, [k]: v }), {});
console.log(viaReduce, Object.fromEntries(pairs));

🖥️ Output

{ env: 'qa', browser: 'firefox' } { env: 'qa', browser: 'firefox' }

Q6. From the list of orders below, print the IDs of delivered orders over ₹1000, sorted by total from high to low.

const orders = [
  { id: 1, total: 1500, status: "delivered" },
  { id: 2, total: 800, status: "delivered" },
  { id: 3, total: 3200, status: "delivered" },
  { id: 4, total: 5000, status: "cancelled" },
];
Show answer

📄 practice6.js

const orders = [
  { id: 1, total: 1500, status: "delivered" },
  { id: 2, total: 800, status: "delivered" },
  { id: 3, total: 3200, status: "delivered" },
  { id: 4, total: 5000, status: "cancelled" },
];
const ids = orders
  .filter((o) => o.status === "delivered" && o.total > 1000)
  .toSorted((a, b) => b.total - a.total)
  .map((o) => o.id);
console.log(ids);

🖥️ Output

[ 3, 1 ]

🧠 MCQ Quiz: map, filter and reduce

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does map return?
  2. What does [1, 2, 3, 4].filter((n) => n % 2 === 0) return?
  3. What is [1, 2, 3].reduce((a, b) => a + b, 10)?
  4. What happens with [].reduce((a, b) => a + b)?
  5. What does find return when nothing matches?
  6. What is [].every((x) => x > 0)?
  7. What does [1, 2].map((n) => { n * 2 }) return?
  8. Which method should you use to check whether at least one item matches?
  9. What does Object.groupBy(items, (i) => i.type) return?
  10. What does [0, "a", "", 5].filter(Boolean) return?

💼 Interview Questions and Answers

Q1. Explain map, filter and reduce in one sentence each.

  • map transforms every element and returns a new array of the same length.
  • filter returns a new array containing only the elements for which the callback returns truthy.
  • reduce combines all elements into a single value (number, object, array) by repeatedly applying a callback to an accumulator.

None of them mutate the original array (unless the callback mutates the objects inside it).

Q2. What is the difference between map and forEach?

map returns a new array built from the callback’s return values, so it is for transforming data and can be chained. forEach returns undefined and is only for side effects such as logging. Neither can be stopped early, and neither waits for async callbacks.

Q3. Implement map and filter using reduce.

📄 implement.js

const myMap = (arr, fn) => arr.reduce((acc, x, i) => [...acc, fn(x, i)], []);
const myFilter = (arr, fn) => arr.reduce((acc, x, i) => (fn(x, i) ? [...acc, x] : acc), []);

console.log(myMap([1, 2, 3], (n) => n * 10));
console.log(myFilter([1, 2, 3, 4], (n) => n > 2));

⌨️ Terminal

node implement.js

🖥️ Output

[ 10, 20, 30 ]
[ 3, 4 ]

It shows that reduce is the most general of the three. In real code use the built-in methods; they are clearer and faster.

Q4. A test asserts that every row of a results table has a valid price, and it passes even when the table fails to load. Why?

If no rows are found, the array is empty, and [].every(fn) is true. The assertion is vacuously satisfied. Assert the row count first (expect(rows.length).toBeGreaterThan(0), or toHaveCount in Playwright), then check every row.


Advertisement

❓ Frequently Asked Questions

🤔 Do map, filter and reduce change the original array?

No, they return new values. But if the callback changes properties of objects inside the array, those objects are changed, because they are shared references.

🤔 When should I use a for loop instead of map/filter/reduce?

When you need to stop early (use for...of with break, or find/some), when you need await step by step, or when a reduce becomes hard to read.

🤔 Is reduce hard to read?

It can be. For sums and counts it is fine; for complex shapes, a plain loop or Object.groupBy may be clearer.

🤔 Are these methods slow?

For typical test data (hundreds or thousands of items) the difference is negligible. Choose clarity first.


🏁 Summary

  • map transforms every item into a new array of the same length.
  • filter keeps the items that pass a test; filter(Boolean) removes falsy values.
  • reduce combines items into one value; always pass an initial value.
  • find, findLast, findIndex, some and every search and stop early; every is true for an empty array.
  • Chain methods into readable pipelines and use Object.groupBy to group results.

Next, continue with Lesson 31: Destructuring and Spread.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in