Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce Multidimensional Array of Numbers

Tags:

javascript

How can I find the sum of all the numbers in the following multidimensional array by the Array.prototype.reduce() function:

var arr = [["one",3],["five",15],["ten",30],["twenty",40]];

I know how to do that using for loop, but just wondering...

like image 701
Farooq AR Avatar asked Mar 13 '26 19:03

Farooq AR


1 Answers

You can do it like this,

var sum = [["one",3],["five",15],["ten",30],["twenty",40]].reduce(function(a,b){
  return a + b[1];
}, 0);

In the above code, 0 passed as a second argument is the initial value to be used in the calculation.

like image 200
Rajaprabhu Aravindasamy Avatar answered Mar 15 '26 09:03

Rajaprabhu Aravindasamy