Javascript: Array Reduce

Here is a simple example of using reduce for adding all values in an array

let add = (...args) => {
  return args.reduce(function(a, b) {
    return a + b; }, 0);
};
let args = [3, 5, 7];
console.log(add(...args));

Clean, right?

In regular JS or ES5, you’d do something like:

var total = 0;
var numbers = [3, 5, 7];
for (var i = 0; i < numbers.length; i++) {
  total += numbers[i];
}

You can simplify the above reduce example to

[3, 5, 7].reduce(function (a, b) {return a + b; }, 0);

I'd say reduce makes it simpler and easier. Read more about it here

Uncategorized

Leave a Reply

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