map, filter and reduce in JavaScript

HTML, CSS & JS 2 min read
Short answer

map transforms each item into a new array of the same length. filter keeps items matching a test. reduce collapses the array into a single value.

javascript
const videos = [
  { title: 'Intro to Python', views: 197, track: 'python' },
  { title: 'PHP Web Form',    views: 259, track: 'php' },
  { title: 'Racket Install',  views: 696, track: 'racket' },
];

const titles  = videos.map((v) => v.title);
const popular = videos.filter((v) => v.views > 200);
const total   = videos.reduce((sum, v) => sum + v.views, 0);

They chain, and each returns a new array — the original is untouched:

javascript
const result = videos
  .filter((v) => v.views > 200)
  .sort((a, b) => b.views - a.views)
  .map((v) => `${v.title} (${v.views})`);

#Grouping with reduce

javascript
const byTrack = videos.reduce((acc, v) => {
  (acc[v.track] ??= []).push(v.title);
  return acc;
}, {});

The return acc is essential — the block's return value becomes the next accumulator.

Modern runtimes have a purpose-built method that is clearer:

javascript
const byTrack = Object.groupBy(videos, (v) => v.track);

#Use the right tool

GoalMethod
New array, same lengthmap
Fewer itemsfilter
One valuereduce
First matchfind / findIndex
Yes or nosome / every
Side effects onlyfor...of

Do not use map when you are not producing a new array — you build one and discard it, and it misleads the next reader. Use for...of or forEach.