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