最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reduce Multidimensional Array of Numbers - Stack Overflow

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论