map, filter and reduce in JavaScript
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.
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:
const result = videos
.filter((v) => v.views > 200)
.sort((a, b) => b.views - a.views)
.map((v) => `${v.title} (${v.views})`);#Grouping with reduce
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:
const byTrack = Object.groupBy(videos, (v) => v.track);#Use the right tool
| Goal | Method |
|---|---|
| New array, same length | map |
| Fewer items | filter |
| One value | reduce |
| First match | find / findIndex |
| Yes or no | some / every |
| Side effects only | for...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.