AppDividend
Latest Code Tutorials

Javascript Reduce Example | Javascript Array reduce() Function

0

Javascript reduce() method is used to apply a function to each element in the array to reduce the array to a single value. Javascript reduce method executes the provided function for each value of an array from left-to-right. The return value of a function is stored in an accumulator. 

JavaScript Array reduce() is one of the pioneers function of functional programming. We need to use a reduce() function when you want to add them all up.

Javascript Reduce

Content Overview

It is similar to both Javascript map() and Javascript filter() but, it differs in the callback arguments.

The callback now receives an accumulator (it accumulates all the return values. Its value is the accumulation of a previously returned accumulations), a current value, a current index, and finally, the whole array. 

If you don’t pass the initial value, the reducer will assume a first item in your array as your initial value.

This worked fine in some examples because we were adding up the list of numbers.

#Syntax of Reduce Javascript

The syntax of the JS reduce() function is the following.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

# or

array.reduce(callback[, initialValue]);
  1. function(total, currentValue, index, arr): It is a required parameter and used to run for each element of the array. It contains four-parameters which are listed below:
    1. total: It is the required parameter and used to specify an initialValue or the previously returned value of a function.
    2. currentValue: It is the required parameter and used to determine the value of a current element.
    3. currentIndex: It is the optional parameter and used to specify an array index of the current element.
    4. arr: It is the optional parameter and used to determine an array object the current element belongs to.
  2. initialValue: It is the optional parameter and used to specify the value to be passed to the function as an initial value.

Let us take the example of the reduce function and see how this works.

// server.js

const data = [5, 10, 15, 20, 25];

const res = data.reduce((total,currentValue) => {
  return total + currentValue;
});

console.log(res); // 75
  1. In this example, the reduce() method accepts two parameters, the total and the current value.
  2. The reduce() method cycles through each value in the array much like it would in the for-loop.
  3. In this specific example, we want to add a current value to the total values.
  4. The calculation is repeated for each value in an array, but each time a current value changes to the next value in the array, moving right.
  5. When there are no more values left in the array, reduce() method returns the total value.

#Flattening arrays with Javascript reduce method

We can use the reduce to flatten the nested amounts into the single array.

We set the initial value to an empty array and then concatenate the current value to the total.

// server.js

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flatValues = data.reduce((total, value) => {
  return total.concat(value);
}, []);

console.log(flatValues);

Javascript Reduce Example Tutorial

You must return something for a reduce function to work.

Always double-check and make sure that you’re returning the value you want.

When your reducer function is called, its return value becomes the new previousValue argument for next time the reducer function is called. That’s the magic.

After the reducer function is called and given the very last object in the array, its return value will be the return value of reduce() function.

#ES6 Syntax of Javascript reduce() function

See the following code.

// app.js

const pounds = [11.21, 19.21, 46.21];

const sum = pounds.reduce((total, amount) => total + amount); 

console.log(sum);

See the output.

➜  es git:(master) ✗ node app
76.63
➜  es git:(master) ✗
  1. In this example, Reduce accepts the two parameters, the total and the current amount.
  2. The reduce() method cycles through each number in the array, much like it would in a for-loop.
  3. When the loop starts, the total value is the number on the far left (11.21), and the current amount is the one next to it which is (19.21).
  4. In this particular example, we want to add the current amount to the total.
  5. The calculation is repeated for each amount in the array, but each time the current value changes to the next number in the array, moving right.
  6. When there are no more numbers left in the array, the method returns the total value.

#How to find average in Javascript

In the above example, instead of logging the sum, what you could do is to divide the sum by a length of the array before you return the final value.

The way to do this is by taking advantage of the other arguments in the reduce method.

The first of those arguments is the index. Much like a for-loop, the index refers to the number of times the reducer has looped over the array.

The last argument is the array itself.

See the following code example.

// app.js

const pounds = [11, 21, 16];

const avg = pounds.reduce((total, amount, index, array) => {
  total += amount;
  if (index === array.length - 1) {
    return total / array.length;
  } else {
    return total;
  }
});

console.log(avg);

See the output.

➜  es git:(master) ✗ node app
16
➜  es git:(master) ✗

#How to find repeated items in array in Javascript

Let’s say you have the collection of items, and you want to know how many of each item is in the collection.

In this scenario, the Javascript reduce method can help us.

// app.js

const pounds = [11, 21, 16, 19, 46, 29, 46, 19, 21];

const count = pounds.reduce( (data, pound) => {
  data[pound] = (data[pound] || 0) + 1 ;
  return data;
} , {})

console.log(count);

See the output.

➜  es git:(master) ✗ node app
{ '11': 1, '16': 1, '19': 2, '21': 2, '29': 1, '46': 2 }
➜  es git:(master) ✗

To tally several items in an array, our initial value must be an empty object, not an empty array.

Since we are going to be returning the object, we can now store key-value pairs in the total.

On our first pass, we want the name of the first key to be our current value, and we want to give it the value of 1.

This gives us the object with all the numbers as keys, each with a value of 1.

We want an amount of each number to increase if they repeat.

To do this, on our second loop, we check if the total contains the key with a current number of the reducer.

If it doesn’t, then we create it. If it does, then we increment the value by one.

#Conclusion

If you don’t pass the initial value, the reduce will assume the first item in your array as your initial value.

Another most common mistake is to forget to return the total. You must return something for a reduce function to work. Always double-check and make sure that you’re returning a value you want.

Finally, Javascript reduce function example is over. You can find more on MDN.

Recommended Posts

Javascript Array isArray()

JavaScript Array reverse()

Javascript Array lastIndexOf()

Javascript Array toString()

Javascript Array every()

Javascript Array values()

Javascript Array includes()

Javascript Array keys()

Javascript Array findIndex()

Javascript Array indexOf()

Leave A Reply

Your email address will not be published.

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