Skip to content
Velloreth
Programming 9 min read

JavaScript Array Methods: A Practical Reference

map, filter, reduce and friends are the core of modern JavaScript. Learn what each does, when to use it, and the mistakes to avoid.

By

The core three

map

Transforms each element and returns a new array of the same length.

const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.2);
// [12, 24, 36]

The callback receives the element, its index, and the array.

const labels = items.map((item, i) => `${i + 1}. ${item.name}`);

filter

Selects elements that pass a test, returning a new array.

const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter((n) => n % 2 === 0);
// [2, 4, 6]

The result may be shorter than the input, or empty. It is never longer.

reduce

Combines the array into a single value.

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 10

The second argument is the initial value. Always provide it. Without it, reduce uses the first element as the initial accumulator and starts from the second, which breaks on empty arrays and produces surprising results.

// Dangerous: throws on an empty array
[].reduce((a, b) => a + b);

// Safe: returns 0
[].reduce((a, b) => a + b, 0);

reduce can produce any type:

// Group by a key
const byCategory = items.reduce((acc, item) => {
  (acc[item.category] ??= []).push(item);
  return acc;
}, {});

// Count occurrences
const counts = words.reduce((acc, word) => {
  acc[word] = (acc[word] ?? 0) + 1;
  return acc;
}, {});

Searching

find

Returns the first matching element, or undefined.

const user = users.find((u) => u.id === 42);

findIndex

Returns the index of the first match, or -1.

const index = users.findIndex((u) => u.id === 42);

findLast and findLastIndex

Search from the end.

const lastError = logs.findLast((l) => l.level === 'error');

includes

Checks whether a value is present.

[1, 2, 3].includes(2); // true

Note that includes uses SameValueZero, so NaN is found, unlike indexOf.

[NaN].includes(NaN);  // true
[NaN].indexOf(NaN);   // -1

indexOf and lastIndexOf

Return the index of a value, or -1. Use includes for a boolean check.

Testing

some

Returns true if at least one element matches.

const hasAdmin = users.some((u) => u.role === 'admin');

every

Returns true only if all elements match.

const allActive = users.every((u) => u.active);

Both short-circuit. some stops at the first match; every stops at the first failure.

An important detail: every returns true for an empty array, and some returns false. This is mathematically consistent but can surprise.

[].every((x) => x > 0); // true
[].some((x) => x > 0);  // false

Transforming

flat

Flattens one level.

[[1, 2], [3, 4]].flat(); // [1, 2, 3, 4]

flatMap

Maps and flattens in one pass, which is more efficient than map().flat().

const words = ['hello world', 'foo bar'];
const all = words.flatMap((s) => s.split(' '));
// ['hello', 'world', 'foo', 'bar']

flatMap is also the idiomatic way to filter and map at once, by returning an empty array for elements to drop.

const valid = items.flatMap((item) => (item.ok ? [item.value] : []));

slice

Returns a shallow copy of a portion.

const firstThree = arr.slice(0, 3);
const lastTwo = arr.slice(-2);
const copy = arr.slice();

concat

Joins arrays.

const combined = [...a, ...b]; // spread is usually preferred
const combined2 = a.concat(b);

toSorted, toReversed, toSpliced

The non-mutating versions of sort, reverse, and splice.

const sorted = arr.toSorted((a, b) => a - b); // arr unchanged
const reversed = arr.toReversed();
const spliced = arr.toSpliced(1, 2, 'x');

These are the modern replacements for the mutating versions, and they make chaining safe.

Mutating methods

These change the original array.

arr.push(x);      // add to the end
arr.pop();        // remove from the end
arr.unshift(x);   // add to the start
arr.shift();      // remove from the start
arr.splice(i, n); // remove n elements at i
arr.sort();       // sort in place
arr.reverse();    // reverse in place
arr.fill(x);      // fill with a value

The mutation is a common source of bugs, especially when an array is shared.

// Bug: sorts the caller's array
function getTopScores(scores) {
  return scores.sort((a, b) => b - a).slice(0, 10);
}

// Fixed: copy first
function getTopScores(scores) {
  return scores.toSorted((a, b) => b - a).slice(0, 10);
}

The sort trap

sort converts elements to strings by default, which produces surprising results for numbers.

[10, 9, 100].sort(); // [10, 100, 9] — string order
[10, 9, 100].sort((a, b) => a - b); // [9, 10, 100] — numeric

Always pass a comparator for numbers. For strings, the default is usually fine, but localeCompare handles accents and case better.

names.sort((a, b) => a.localeCompare(b));

Chaining

The non-mutating methods chain naturally.

const result = orders
  .filter((o) => o.status === 'paid')
  .map((o) => o.total)
  .reduce((sum, t) => sum + t, 0);

Each step is a small, readable transformation. This is the main advantage over a loop.

The cost is intermediate arrays. For a chain over a million elements, that is a million-element array per step. For typical data sizes it does not matter; for hot paths, a single loop is faster.

When to use a loop

Array methods are not always clearer.

// Array methods: two passes
const hasError = logs.filter((l) => l.level === 'error').length > 0;

// Better: short-circuits
const hasError = logs.some((l) => l.level === 'error');
// A loop is clearer for complex logic
let total = 0;
let count = 0;
for (const item of items) {
  if (!item.valid) continue;
  total += item.price;
  count++;
  if (count >= 100) break;
}

The loop has an early exit, two accumulators, and a skip condition. Expressing that with array methods requires reduce with a complex accumulator, which is harder to read.

The rule: use array methods for simple transformations, and a loop when the logic has multiple concerns or early exits.

Performance characteristics

Array methods are not free, and knowing the cost helps you choose.

Each method walks the array once. A chain of three methods walks it three times and allocates two intermediate arrays. For a hundred elements that is irrelevant. For a million, it is measurable.

// Three passes, two intermediate arrays
const result = items
  .filter((i) => i.active)
  .map((i) => i.price)
  .reduce((sum, p) => sum + p, 0);

// One pass, no intermediates
let total = 0;
for (const item of items) {
  if (item.active) total += item.price;
}

The chain is clearer. The loop is faster. The right choice depends on the data size and how hot the path is.

A useful rule: if the array is under a few thousand elements, prefer the chain for readability. If it is in a hot loop or the array is large, measure and consider a single pass.

reduce is the exception to the “one pass” rule, because it can express the whole chain in a single traversal — at the cost of readability.

const total = items.reduce(
  (sum, item) => (item.active ? sum + item.price : sum),
  0,
);

This is one pass and reasonably clear. It is a good middle ground when performance matters but the logic is simple.

Sparse arrays

Array methods skip holes in sparse arrays, which can surprise.

const sparse = [1, , 3]; // a hole at index 1
sparse.map((x) => x * 2); // [2, <hole>, 6] — the hole is preserved
sparse.filter((x) => true); // [1, 3] — the hole is removed

map preserves holes, filter removes them, and forEach skips them. This is rarely what you want, and sparse arrays are best avoided. If you need to fill holes, use Array.from or fill.

const filled = Array.from({ length: 3 }, (_, i) => i + 1); // [1, 2, 3]

Reading unfamiliar chains

When you encounter a long chain in code you did not write, read it in stages rather than all at once. Start from the array and follow the data through each step, noting how the shape changes. A filter keeps the same element type but reduces the count. A map changes the element type. A reduce collapses everything into one value. Once you know the shape at each stage, the chain becomes readable.

A useful habit is to name the intermediate steps when a chain grows past three or four calls. Extracting a step into a named variable documents what the data looks like at that point, and it makes the chain easier to debug because you can log the intermediate value. The chain is a compression of a sequence of operations, and like any compression it trades explicitness for brevity. When the trade stops paying off, expand it.

Practical guidance

  • Use map for transformation, filter for selection, reduce for aggregation.
  • Always pass an initial value to reduce.
  • Use find for one item, filter for many.
  • Use some and every instead of filtering and checking length.
  • Prefer toSorted and toReversed over the mutating versions.
  • Always pass a comparator to sort for numbers.
  • Use flatMap to map and filter in one pass.
  • Use a loop when the logic has early exits or multiple accumulators.

For the related guides, see javascript-object-methods-guide and javascript-destructuring-guide. For the broader context, higher-order-functions-explained and immutability-explained.

Quotable summary

map transforms each element, filter selects elements, and reduce combines them into a single value, and all three return new arrays rather than mutating the original, which makes them safe to chain. Always pass an initial value to reduce, because without it the first element becomes the accumulator and empty arrays throw. Use find for the first match and some or every for boolean checks, rather than filtering and checking length, since those short-circuit. Watch for the mutating methods — push, pop, splice, sort, and reverse change the original array — and prefer the newer toSorted, toReversed, and toSpliced. Always pass a comparator to sort for numbers, because the default converts elements to strings and produces surprising order.

Frequently asked questions

What is the difference between map and forEach?
map returns a new array of transformed values, so it can be chained. forEach returns undefined and is for side effects. If you need the result, use map.
What does reduce do?
reduce walks the array and accumulates a single value, using a callback that receives the accumulator and the current element. It can produce a number, string, object, or another array.
Which array methods mutate the original?
push, pop, shift, unshift, splice, sort, reverse, and fill mutate. map, filter, slice, concat, and the newer toSorted, toSpliced, and toReversed do not.
What is the difference between find and filter?
find returns the first matching element or undefined. filter returns an array of all matches, which may be empty. Use find when you need one item.
What is the difference between some and every?
some returns true if at least one element matches. every returns true only if all elements match. Both short-circuit as soon as the answer is known.
Should I always use array methods instead of loops?
No. Array methods are clearer for transformation and filtering. For complex logic with early exits, multiple accumulators, or performance-critical code, a plain loop is often clearer and faster.