# Array Methods (map, filter, reduce)

> Explain the key array methods in JavaScript. How do map, filter and reduce differ, and when would you use each?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-array-methods
Last updated: 2026-11-28

Difficulty: Beginner

## Question

Explain the key array methods in JavaScript. How do map, filter and reduce differ, and when would you use each?

## Answer

`map`, `filter` and `reduce` are higher-order array methods that take a callback and return a new value without mutating the original array. `map` transforms every element and returns an array of the same length, `filter` keeps the elements whose callback returns truthy, and `reduce` folds the whole array into a single value of any shape, such as a sum, an object or a grouped map.

### What each one returns

| Method | Callback returns | Result | Length |
| --- | --- | --- | --- |
| `map` | The new element | New array | Same as input |
| `filter` | Truthy or falsy | New array | Same or fewer |
| `reduce` | The next accumulator | Any value | n/a |
| `forEach` | Ignored | `undefined` | n/a |
| `find` / `findIndex` | Truthy or falsy | First match or `undefined` / `-1` | n/a |
| `some` / `every` | Truthy or falsy | Boolean, short-circuits | n/a |

The callback receives `(element, index, array)`. `reduce` receives `(accumulator, element, index, array)` and takes an optional initial value as its second argument.

### How reduce works

`reduce` starts with the initial value as the accumulator, calls the callback for each element, and uses whatever the callback returns as the accumulator for the next call. The final accumulator is the result. Always pass an initial value: without one, `reduce` uses the first element as the start, and on an empty array it throws `TypeError: Reduce of empty array with no initial value`.

Use `reduce` when the output shape differs from the input, for example totalling a cart in paise or grouping orders by status. For grouping, `Object.groupBy(items, fn)` (ES2024, available in Node 21+ and all current browsers) is now a clearer alternative.

### Chaining and performance

Because `map` and `filter` return arrays, you can chain them: `orders.filter(isPaid).map(toInvoice)`. Each step creates an intermediate array and loops again. For a few thousand items this does not matter and readability wins. For hot paths over large data, a single `reduce` or a plain `for...of` loop avoids the extra allocations. Iterator helpers (`Iterator.prototype.map`, `.filter`, `.take`) shipped in ES2025 and are available in current Chrome and Node 22+, giving lazy chaining without intermediate arrays.

### Common mistakes

- Using `map` for side effects and ignoring the result. Use `forEach` or `for...of` instead.
- Forgetting to `return` inside a block-body arrow: `arr.map(x => { x * 2 })` gives `[undefined, ...]`.
- `['1', '2', '3'].map(parseInt)` returns `[1, NaN, NaN]` because `map` passes the index as `parseInt`'s radix argument.
- Expecting `forEach` to stop early. It cannot be broken out of; use `for...of` with `break`, or `some`/`find`.
- Mutating methods sneaking in: `sort`, `reverse` and `splice` change the original array. ES2023 added `toSorted`, `toReversed`, `toSpliced` and `with` as non-mutating versions, which matter in React state updates.

**map → filter → reduce, element by element. Edit the input and the callbacks under Tweak. Try find or every to see short-circuiting.**

1. **map**: Runs the callback on every element and returns a new array of the same length.
2. **filter**: Keeps only elements whose callback returns truthy.
3. **reduce**: Folds the array into one value using an accumulator.
4. **Immutability**: None of these change the original array.

## Code examples

### filter, map and reduce on orders

```
const orders = [
  { id: 1, status: 'PAID', amountPaise: 24900 },
  { id: 2, status: 'FAILED', amountPaise: 9900 },
  { id: 3, status: 'PAID', amountPaise: 15000 },
  { id: 4, status: 'PAID', amountPaise: 5000 },
];

const paidTotal = orders
  .filter((o) => o.status === 'PAID')
  .map((o) => o.amountPaise)
  .reduce((sum, amt) => sum + amt, 0);

console.log(paidTotal / 100); // rupees
console.log(orders.length);   // original unchanged
```

filter narrows, map reshapes, reduce aggregates. The initial value 0 keeps reduce safe on an empty array.

### reduce to build an object, and Object.groupBy

```
const orders = [
  { id: 1, city: 'Pune' }, { id: 2, city: 'Delhi' }, { id: 3, city: 'Pune' },
];

const countByCity = orders.reduce((acc, o) => {
  acc[o.city] = (acc[o.city] ?? 0) + 1;
  return acc;               // always return the accumulator
}, {});
console.log(countByCity);

// ES2024: group without writing reduce by hand
const grouped = Object.groupBy(orders, (o) => o.city);
console.log(Object.keys(grouped));
```

reduce can build any shape. Object.groupBy covers the common grouping case directly in modern runtimes.

### Classic pitfalls

```
console.log(['1', '2', '3'].map(parseInt));          // [ 1, NaN, NaN ]
console.log(['1', '2', '3'].map(Number));            // [ 1, 2, 3 ]

console.log([1, 2].map((x) => { x * 2; }));          // [ undefined, undefined ]

const scores = [40, 10, 30];
const sorted = scores.toSorted((a, b) => a - b);     // ES2023, non-mutating
console.log(sorted, scores);
```

map passes (value, index), which breaks parseInt. A block-body arrow needs an explicit return. toSorted sorts without touching the original.

## Key points

- map keeps length, filter can shrink, reduce returns any shape
- Always give reduce an initial value
- forEach returns undefined and cannot be stopped early
- sort, reverse and splice mutate; toSorted, toReversed, toSpliced do not (ES2023)
- Object.groupBy (ES2024) replaces many hand-written grouping reduces

## Common follow-up questions

- Implement your own version of Array.prototype.map or reduce.
- Why does \['1','2','3'\].map(parseInt) return \[1, NaN, NaN\]?
- When would you choose a for loop over map/filter?
- How would you flatten a nested array, and what does flatMap do?

## Interview tips

- Describe each method by what it returns; that is the cleanest way to contrast them
- Expect to write a polyfill for map or reduce; practise one with the index and initial-value handling
- Mention the ES2023 non-mutating methods if React or immutability comes up

## Concepts covered

map, filter, reduce, Immutability, Method Chaining, Array.prototype

Previous: [String Methods & Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-string-methods) · Next: [Destructuring & Spread/Rest](https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Error Handling (try/catch/finally)](https://www.internhack.in/learn/interview/javascript-interview/js-error-handling)
- [== vs === Equality Operators](https://www.internhack.in/learn/interview/javascript-interview/js-equality-operators)
- [Arrow Functions vs Regular Functions](https://www.internhack.in/learn/interview/javascript-interview/js-arrow-functions)
- [Template Literals & String Interpolation](https://www.internhack.in/learn/interview/javascript-interview/js-template-literals)
- [null vs undefined](https://www.internhack.in/learn/interview/javascript-interview/js-null-undefined)
- [JSON: parse, stringify & Common Pitfalls](https://www.internhack.in/learn/interview/javascript-interview/js-json-parse-stringify)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
