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

Notice: Theme without comments.php is deprecated since version 3.0.0 with no alternative available. Please include a comments.php template in your theme. in /var/www/fahdmurtaza.com/public_html/wp-includes/functions.php on line 3984

Leave a Reply

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