Reputation: 304
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...
Upvotes: 2
Views: 3973
Reputation:
Break this down into sub-problems.
First, write getNumbers
to get an array of numbers from the input.
It uses getNumber
, which get the second element in each little array.
sum
adds up the numbers in an array using reduce
,
which uses the add
function to add two numbers
function sum(arr) { return arr.reduce(add, 0); }
function add(a, b) { return a + b; }
function getNumber(pair) { return pair[1]; }
function getNumbers(arr) { return arr.map(getNumber); }
var arr = [["one",3],["five",15],["ten",30],["twenty",40]];
console.log(sum(getNumbers(arr)));
Upvotes: 1
Reputation: 67207
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.
Upvotes: 9