🟨 JavaScript Basics

JavaScript Array Methods Explained: map, filter, reduce, and Friends

By The CodeCraft Team··9 min read
JavaScript code showing array methods chained together

JavaScript arrays come with over 30 built-in methods. You don't need all of them, but the dozen below cover almost every real-world task — and using them well makes code shorter and easier to read.

Transform: map

const users = [{ name: 'Ada' }, { name: 'Linus' }];
const names = users.map(u => u.name);
// ['Ada', 'Linus']

Keep matches: filter

const adults = people.filter(p => p.age >= 18);

Aggregate: reduce

const total = cart.reduce((sum, item) => sum + item.price, 0);

Search: find, findIndex, includes

const user = users.find(u => u.id === 42);
const idx  = users.findIndex(u => u.id === 42);
const hasAdmin = roles.includes('admin');

Test: some and every

cart.some(item => item.price > 100);  // true if any
cart.every(item => item.inStock);     // true if all

Flatten: flat and flatMap

[[1,2],[3,4]].flat();         // [1,2,3,4]
sentences.flatMap(s => s.split(' '));

Chaining for clarity

const totalOver18 = users
  .filter(u => u.age >= 18)
  .map(u => u.spending)
  .reduce((sum, n) => sum + n, 0);

Mutation vs new array

  • Returns new array — map, filter, slice, concat, flat
  • Mutates the array — push, pop, sort, splice, reverse
  • Modern non-mutating versions — toSorted, toReversed, toSpliced

Common mistakes

  • Using forEach when you actually wanted map
  • Forgetting reduce's initial value (sum starts as undefined)
  • Sorting in place inside React state — use toSorted()

Frequently asked questions

Are these methods slower than for loops?

Slightly, but never enough to matter outside hot loops on huge arrays. Readability wins.

When should I use forEach?

When you only need a side effect and don't need a new array. Otherwise prefer map.

External references

Enjoyed this article?

Share it with a fellow developer or explore more tutorials in our blog.

More articles

Related articles