map vs filter vs reduce

Array.map  map all values to an expression.

1] Expression value + 1 is applied to every item in the original array.

2] .map() returns a modified copy of the array leaving original untouched.

3] Result: [2,3,4,5,6,7,8] (a copy of the original array is created.)

Array.filter  keep all that match a condition.

NOTE: there is a small mistake in the animation. It should return [6,7], not [6,7,8]. I’ll fix it shortly. . .

1] function value > 5 is applied to every item in the original array.

2] .filter() returns a modifiedcopyof the array – the original is still available!

3] Result: [6,7,8] (only values that passed the condition.)

Array.reduce – reduce all items to a single value.

A common use for a reducer is combining prices of all items in shopping cart.

What makes reduce unique is that it uses an accumulator.

Accumulator is required to be set to a starting value. Here it is 0.

1 ] Reducer function F takes value and accumulator.

2 ] In this example .reduce(vareturns the sum of all values.

3 ] Result: 28 (the sum of all numbers in the original array)

Sources:

https://medium.com/@js_tut/map-filter-and-reduce-animated-7fe391a35a47

https://stackoverflow.com/questions/49934992/main-difference-between-map-and-reduce

Author:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.