Front-End · 9 min read · Updated

JavaScript Array Methods Cheat Sheet: map, filter, reduce and More

A practical cheat sheet of JavaScript array methods – map, filter, reduce, find, some, toSorted and more – with clear examples and the mistakes to avoid.

Javascript array methods: binary source code
Photo: Markus Spiske via Rawpixel (CC0)

Arrays are everywhere in front-end work: products in a shop, rows in a table, results from an API, menu items in a navbar. Knowing the right array method turns ten lines of loop code into one clear line. It is also one of the most common topics in JavaScript interviews.

This cheat sheet groups the JavaScript array methods by what you want to do, shows each with a short example, and points out which ones change the original array. All examples use this small data set:

const products = [
  { name: 'Filter coffee powder', price: 240, category: 'grocery', inStock: true },
  { name: 'Cotton towel', price: 199, category: 'home', inStock: false },
  { name: 'Brass lamp', price: 1450, category: 'home', inStock: true },
  { name: 'Jaggery', price: 90, category: 'grocery', inStock: true }
];

Tip: New to arrays? Read the JavaScript arrays lesson and the lesson on functions first – almost every method here takes a callback function, usually written as an arrow function.

JavaScript array methods: the quick reference table

MethodReturnsChanges original?Use it to…
map(fn)New array, same lengthNoTransform every item
filter(fn)New array, same or shorterNoKeep items that pass a test
reduce(fn, start)A single valueNoTotal, count or build one result
find(fn) / findLast(fn)First / last matching item or undefinedNoGet one item
findIndex(fn)Index or -1NoGet the position of an item
some(fn) / every(fn)true or falseNoCheck if any / all items pass
includes(value)true or falseNoCheck if a value is present
forEach(fn)undefinedNo (by itself)Run side effects, such as updating the DOM
at(index)One itemNoRead from the end with negative numbers
slice(start, end)New arrayNoCopy part of an array
concat(), spread [...a, ...b]New arrayNoJoin arrays
flat() / flatMap(fn)New arrayNoFlatten nested arrays
join(sep)StringNoMake a string from items
toSorted(), toReversed(), toSpliced(), with()New arrayNoSort, reverse, edit without mutating
push, pop, shift, unshiftLength or removed itemYesAdd or remove at the ends
sort(), reverse(), splice(), fill()The same array (splice returns removed items)YesChange the array in place

Transforming: map

map calls your function on each item and collects the return values into a new array of the same length.

const names = products.map(p => p.name);
// ['Filter coffee powder', 'Cotton towel', 'Brass lamp', 'Jaggery']

const withGst = products.map(p => ({ ...p, priceWithGst: Math.round(p.price * 1.18) }));
// each object gets a new property; the originals are untouched

Watch out: If you use curly braces in an arrow function, you must write return. products.map(p => { p.name }) gives an array of undefined. To return an object directly, wrap it in brackets: p => ({ … }).

Selecting: filter, find, findIndex

const available = products.filter(p => p.inStock);       // 3 items
const cheap = products.filter(p => p.price < 200);        // Cotton towel, Jaggery

const lamp = products.find(p => p.name === 'Brass lamp'); // the object
const missing = products.find(p => p.price > 5000);       // undefined

const towelIndex = products.findIndex(p => p.name === 'Cotton towel'); // 1

Use filter when you want all matches (always an array, possibly empty) and find when you want one item. A common beginner mistake is using filter(…)[0] where find is clearer and stops at the first match. findLast and findLastIndex search from the end.

Checking: some, every, includes

products.some(p => !p.inStock);      // true  – at least one is out of stock
products.every(p => p.price > 50);   // true  – all cost more than 50

const cities = ['Chennai', 'Madurai', 'Puducherry'];
cities.includes('Madurai');          // true
cities.includes('madurai');          // false – comparison is case-sensitive

includes compares values directly, so it works well for strings and numbers. For arrays of objects, use some with a condition, because two different objects are never equal even if their contents match. Unlike indexOf, includes also finds NaN.

Combining: reduce

reduce walks through the array carrying an accumulator – a running result – and returns it at the end. Always pass a starting value as the second argument.

const total = products.reduce((sum, p) => sum + p.price, 0); // 1979

const countByCategory = products.reduce((acc, p) => {
  acc[p.category] = (acc[p.category] || 0) + 1;
  return acc;
}, {});
// { grocery: 2, home: 2 }

reduce is powerful but can be hard to read. If a map plus filter, or a simple for…of loop, says the same thing more clearly, prefer that. For grouping, there is now a dedicated tool.

Grouping: Object.groupBy

Object.groupBy(items, fn) groups items by the string your function returns. It has been available in all major browsers since March 2024 (Baseline). It is a static method on Object, not an array method.

const groups = Object.groupBy(products, p => p.category);
// { grocery: [coffee, jaggery], home: [towel, lamp] }

groups.home.length; // 2

The result is a null-prototype object, so methods like groups.hasOwnProperty do not exist on it – use Object.hasOwn(groups, 'home') or 'home' in groups. If you need non-string keys, Map.groupBy returns a Map.

Sorting safely: sort vs toSorted

sort() has two traps. It changes the original array, and without a compare function it sorts items as strings, so [100, 25, 3].sort() gives [100, 25, 3] – “1” comes before “2” and “3”.

const byPrice = products.toSorted((a, b) => a.price - b.price);   // cheapest first, original unchanged
const byPriceDesc = products.toSorted((a, b) => b.price - a.price);

const byName = products.toSorted((a, b) => a.name.localeCompare(b.name));

const updated = products.with(0, { ...products[0], price: 260 }); // replace item 0 in a copy

toSorted, toReversed, toSpliced and with are the copying versions of sort, reverse, splice and index assignment. They have been Baseline since July 2023. They are especially useful in React state, where you must not mutate existing arrays.

Flattening, slicing and joining

  • [[1, 2], [3, [4]]].flat() → [1, 2, 3, [4]]. Pass a depth, such as flat(2), or Infinity for all levels.
  • flatMap maps then flattens one level – handy when each item produces several results, such as splitting tag strings into one list of tags.
  • slice(0, 3) copies the first three items; slice(-2) copies the last two. The original is unchanged.
  • at(-1) reads the last item, cleaner than arr[arr.length - 1].
  • ['HTML', 'CSS', 'JS'].join(' · ') → "HTML · CSS · JS".

Creating arrays from other things

Many browser APIs give you something that looks like an array but is not one. document.querySelectorAll returns a NodeList, which has forEach but no map or filter. Convert it first:

  • Array.from(document.querySelectorAll('.card')) or [...document.querySelectorAll('.card')] gives a real array.
  • Array.from({ length: 5 }, (_, i) => i + 1) creates [1, 2, 3, 4, 5] – handy for page numbers or star ratings.
  • Array.from(new Set(cities)) removes duplicate values.
  • Object.entries(obj) turns an object into an array of [key, value] pairs so you can use array methods on it; Object.fromEntries turns it back.
  • Array.isArray(value) is the reliable way to check whether something is an array – typeof returns "object" for arrays.

Try it: chaining methods

Methods that return arrays can be chained. Run this demo to see several of them work on the product list, with results printed on the page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Array methods demo</title>
<style>
  body { font-family: system-ui, sans-serif; margin: 20px; }
  pre { background: #0f172a; color: #e2e8f0; padding: 14px; border-radius: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
  <h1>Array methods demo</h1>
  <pre id="out"></pre>
<script>
  const products = [
    { name: 'Filter coffee powder', price: 240, category: 'grocery', inStock: true },
    { name: 'Cotton towel', price: 199, category: 'home', inStock: false },
    { name: 'Brass lamp', price: 1450, category: 'home', inStock: true },
    { name: 'Jaggery', price: 90, category: 'grocery', inStock: true }
  ];
  const rupee = n => '\u20B9' + n.toLocaleString('en-IN');
  const lines = [];

  const inStockNames = products
    .filter(p => p.inStock)
    .toSorted((a, b) => a.price - b.price)
    .map(p => `${p.name} (${rupee(p.price)})`);
  lines.push('In stock, cheapest first:\n  ' + inStockNames.join('\n  '));

  const total = products.reduce((sum, p) => sum + p.price, 0);
  lines.push('Total of all items: ' + rupee(total));

  lines.push('Any out of stock? ' + products.some(p => !p.inStock));
  lines.push('Most expensive: ' + products.toSorted((a, b) => b.price - a.price).at(0).name);

  const groups = Object.groupBy(products, p => p.category);
  for (const [cat, items] of Object.entries(groups)) {
    lines.push(`${cat}: ${items.map(p => p.name).join(', ')}`);
  }

  lines.push('Original order kept: ' + products.map(p => p.name).join(', '));
  document.getElementById('out').textContent = lines.join('\n\n');
</script>
</body>
</html>

Read a chain from top to bottom like a recipe: keep the in-stock items, sort them by price, turn each into a label. Put each method on its own line for readability.

forEach vs map vs for…of

  • Use map when you want a new array back.
  • Use forEach for side effects – adding elements to the page, for example – when you need no result. It cannot be stopped early with break.
  • Use for…of when you need break, continue or await inside the loop. See JavaScript loops.
  • Do not use map just to loop – creating an unused array confuses readers.

Practice tasks

Try these with the sample products before looking anything up. They are similar to questions asked in fresher interviews – see HTML and CSS Interview Questions for the wider set.

  1. Get an array of the names of products that cost more than 150, in capital letters.
  2. Find the total value of only the in-stock items.
  3. Check whether every grocery item is in stock.
  4. Make a copy of the list sorted by name, without changing the original.
  5. Build an object that maps each product name to its price, using Object.fromEntries and map.

If you can solve all five in a few minutes, you know the methods most front-end code relies on.

Common mistakes with JavaScript array methods

  • Forgetting return inside curly-brace arrow functions.
  • Calling sort() on numbers without (a, b) => a - b.
  • Mutating state by accident with sort, reverse or splice – use the to… versions or copy first with [...arr].
  • Leaving out the starting value in reduce, which throws an error on an empty array.
  • Expecting includes to find an object by its contents.
  • Using async callbacks inside forEach and expecting it to wait. Use for…of with await, or Promise.all with map. See Fetch and async.

JavaScript array methods are also the backbone of rendering lists in React – see React lists and keys – and of DOM work in general, covered in JavaScript DOM Basics for Designers. For the language features used here, such as arrow functions and spread, see Modern JavaScript (ES6+).

Frequently asked questions

What is the difference between map and forEach?

map returns a new array built from your callback’s return values. forEach returns undefined and is used only for side effects such as updating the page.

Which array methods change the original array?

push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin mutate the array. map, filter, reduce, slice, concat, flat and the newer toSorted, toReversed, toSpliced and with return new values instead.

Why does sort() put 100 before 25?

Without a compare function, sort converts items to strings and compares them character by character. Pass (a, b) => a – b to sort numbers in ascending order.

When should I use find instead of filter?

Use find when you need a single item; it returns the first match or undefined and stops searching early. Use filter when you need every match as an array.

Can I use toSorted and Object.groupBy in production?

Yes, in current browsers. toSorted has been Baseline since July 2023 and Object.groupBy since March 2024. If you must support older browsers, check your audience or use a build tool with polyfills.

Further reading

Keep reading

All articles