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 badges2 Answers
Reset to default 9You 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
版权声明:本文标题:javascript - Reduce Multidimensional Array of Numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744046325a2524187.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论