Explain the javascript Reduce with an examples

Basic Introduction To Reduce

Where do I use it?

The reduce() method can be used on any valid array of items.

What does it do?

When called, reduce() executes a reducer function (provided by you) on each item of the array, resulting in a single output value that is called the accumulator.

Use case #1 (ES6+)

Use this when:

You want to add up all the values inside an array.

const myWallet = [15, 5, 50];
const sum = mywallet.reduce ( (total, amount) => total + amount);


How it works:

The reducer function will loop through each array item and add each amount found to the accumulator total.

Use case # 2- Counting

Use this when:

You want to know how many copies of an item are found in an array

const pets = ['dog', 'cat', 'bird', 'cat'];

 const count = pets.reduce ( (count, pet) => {
count [pet] = (count [pet] | | 0) + 1;
return count;
} , { } )
How it works:

To count the occurrence of each item of the array, our initial value needs to be an object, this way we can return key-value pairs as the result. The reducer sets each item found to an initial value of 1, then if it finds the item again, that value gets incremented and the result is assigned to the object key

Use Case #3- Flattening

Use this when:

You want to flatten arrays from inside an object

const colorData = [

{colors: ['blue', 'green ']},

{colors : ['green', 'red']}
];
 const flatColors = colorData.reduce ( (total, current) => {
current.colors.forEach (color => total.push (color) )
return total;
} , [ ])
How it works:

Data is often nested in complicated ways. Using this function will loop through every instance of colors from the array and push each value found to the accumulator, resulting in a flattened array containing all colors found inside the object

Useful Tips

Tip #1

If an initial value is not passed to the reduce function, it will automatically assume that the first item in your array is the initial value. This worked in the first example because we only

added up a list of numbers, but it is needed in the two other examples because we want to loop through the array with an empty initial value and keep on adding to that in order to

build the result.

Tip #2

Don’t forget to return the total (the accumulator). Always check twice that you are returning the value that you need.

Tip #3

Remember, the reducer function can take 2 parameters:

The callback (function to run on every element of the array)

The initial value (value to use in the first callback executed)

Tip #4

Remember, the callback function has two required parameters:

the accumulator and the current value.

Leave a Reply

Your email address will not be published.