Reduce in javascript

broken image
broken image

Say you have a shopping list as an array of strings, but you want to remove all of the foods that you don't like from the list. That new value could be an array, the length of which might be different than the original. On the other hand, reduce() indicates that all elements of the original array will get transformed into a new value. It tells the compiler (and others reading your code) that every element in the original array will be transformed and returned as a new array of equal length. Generally, if you plan to return an array, map() is often a better option.

broken image

Syntax const newValue = arr.reduce(function(accumulator, currentValue, index, array) ) // initialize the accumulator as an empty object While others like map() and filter() provide specific functionality, reduce() can be used to transform an input array into any output you desire, all while preserving the original array. Reduce() is like the Swiss Army knife of array methods.

broken image

The single value that is returned can be of any type. The reduce() method reduces an array of values down to just one value.

broken image