DEV Community

Cover image for Map, Filter, & Reduce in JavaScript

Map, Filter, & Reduce in JavaScript

Muhannad on January 18, 2020

This post is a basic walkthrough of JavaScript's map, filter, and reduce methods that provides practical use cases of functional programming in Jav...
Collapse
 
cappe987 profile image
Casper

Ideally, you shouldn't modify the original array at all. Funtional programming encourages immutability. From a strictly functional perspective you should really only use forEach() for IO operations, like changing the DOM.

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

I appreciate how you've taken this explanation upon yourself. I think there's a revision in here, though; reduce is a for with a return value, map is a specialized reduce that gives back a new array.

Quite literally, anything you can do with a for loop, you can do with reduce

const pets = ["cat", "dog", "birb"]

pets.reduce((item, acc) => 
  console.log(item),
  null
) // effectively a logging `for`

pets.reduce((item, acc) => 
  /(cat|dog)/.test(item) ? [...acc, item] : acc,
  []
) // self-implemented `filter`

pets.reduce((item, acc) =>
  [...acc, `cute ${item}`],
  []
) // self-implemented `map`
Collapse
 
man2006 profile image
Muhannad

That's an interesting point that I hadn't considered, I'll update the post to reflect that!

Collapse
 
vdale profile image
v-dale

The filter example should return the even numbers. Isn't it?

Collapse
 
man2006 profile image
Muhannad

You're right, I've updated the typo!