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?

1
  • 1
    index 3 value is not 5? Commented Sep 30, 2016 at 1:07

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.
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

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.