admin 管理员组

文章数量: 1086019

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...

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...

Share Improve this question asked Jul 20, 2016 at 6:24 Farooq ARFarooq AR 3045 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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.

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)));

本文标签: javascriptReduce Multidimensional Array of NumbersStack Overflow