admin管理员组文章数量:1426233
I have two arrays:
a = [12, 50, 2, 5, 6];
and
b = [0, 1, 3];
I want to sum those arrays value in array A
with exact index value as array B
so that would be 12+50+5 = 67
. Kindly help me to do this in native javascript. I already tried searching but I can't find any luck. I found related article below, but I can't get the logic
indexOf method in an object array?
I have two arrays:
a = [12, 50, 2, 5, 6];
and
b = [0, 1, 3];
I want to sum those arrays value in array A
with exact index value as array B
so that would be 12+50+5 = 67
. Kindly help me to do this in native javascript. I already tried searching but I can't find any luck. I found related article below, but I can't get the logic
indexOf method in an object array?
Share Improve this question edited May 23, 2017 at 10:34 CommunityBot 11 silver badge asked Sep 30, 2016 at 1:03 MarlZ15199MarlZ15199 2882 silver badges17 bronze badges 1- 1 index 3 value is not 5? – passion Commented Sep 30, 2016 at 1:07
5 Answers
Reset to default 3You can simply do as follows;
var arr = [12, 50, 2, 5, 6],
idx = [0, 1, 3],
sum = idx.map(i => arr[i])
.reduce((p,c) => p + c);
console.log(sum);
sumAIndiciesOfB = function (a, b) {
var runningSum = 0;
for(var i = 0; b.length; i++) {
runningSum += a[b[i]];
}
return runningSum;
};
logic explained:
loop through array b. For each value in b, look it up in array a (a[b[i]]
) and then add it to runningSum
. After looping through b you will have summed each index of a
and the total will be in runningSum
.
b
contains the indices of a
to sum, so loop over b
, referencing a
:
var sum=0, i;
for (i=0;i<b.length;i++)
{
sum = sum + a[b[i]];
}
// sum now equals your result
You could simply reduce array a
and only add values if their index exists in array b
.
a.reduce((prev, curr, index) => b.indexOf(index) >= 0 ? prev+curr : prev, 0)
The result is 12+50+5=67.
Like this:
function addByIndexes(numberArray, indexArray){
var n = 0;
for(var i=0,l=indexArray.length; i<l; i++){
n += numberArray[indexArray[i]];
}
return n;
}
console.log(addByIndexes([12, 50, 2, 5, 6], [0, 1, 3]));
本文标签: javascriptSum specific array values depends on list of index value on other arrayStack Overflow
版权声明:本文标题:javascript - Sum specific array values depends on list of index value on other array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745471942a2659789.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论