2

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?

Community
  • 1
  • 1
MarlZ15199
  • 288
  • 2
  • 17

5 Answers5

3

You 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);
Redu
  • 25,060
  • 6
  • 56
  • 76
2
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.

httpNick
  • 2,524
  • 1
  • 22
  • 34
  • This works, but keep in mind that assigning a function to a variable forces all your function calls to come after assignment, which is not true of functions that are not assigned to variables. – StackSlave Sep 30 '16 at 01:16
2

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
varontron
  • 1,120
  • 7
  • 21
2

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.

Patrick Grimard
  • 7,033
  • 8
  • 51
  • 68
-1

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]));
StackSlave
  • 10,613
  • 2
  • 18
  • 35