-1

I have two Javascript vectors, a and b, of the same length. I want to add b to a. The obvious way is:

for (i=0; i<a.length; ++i)
    a[i] += b[i]

but this requires a loop. I can do:

a.forEach(function(item,index) {
   a[index] += b[index]
})

but this is cumbersome - it requires an unneeded parameter "item". Is there a shorter option? Maybe using some external library?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • 2
    What's the problem with looping? A library will simply add overhead to your code when a simple loop will do the job. And any "shortcut" in a library will be using a loop under the hood anyway. – Andy Mar 19 '16 at 17:18
  • 1
    do you want this python feature: http://stackoverflow.com/questions/16568056/python-nested-list-comprehension-with-two-lists ? I think it's not available: http://es6-features.org/ . – Sombriks Mar 19 '16 at 17:28
  • @Sombriks yes, this is what I meant. – Erel Segal-Halevi Mar 19 '16 at 17:34

2 Answers2

2

There is no built-in JS function to do this without looping. Further any library that implements this is going to use looping to do it also.

So, write yourself a short utility function and then just call that function whenever you want to do this. There's going to be looping somewhere in order to implement this as it is not a native JS feature. If you want to "hide" the looping, then just put it in a utility function and just call the function when you need it.

// returns a new array that is the sum of the two vector arrays
function addVectors(a, b) {
   return a.map(function(item, index) {
       return item += b[index];
   });
}

Or, if you want one array modified in place:

// add one vector to another, modifying the first one
function addToVector(a, b) {
    a.forEach(function(item, index) {
        a[index] += b[index];
    });
    return a;
}

Or, if the unused item argument bothers you for some reason:

// add one vector to another, modifying the first one
function addToVector(a, b) {
    for (var i = 0; i < a.length; i++) {
        a[i] += b[i];
    }
    return a;
}

Note, all of these functions assume a and b are the same length. You would have to specify what you want the behavior to be if they end up not being the same length and you want to check for that. You could throw an exception, just add the parts in common, etc...

For example:

// returns a new array that is the sum of the two vector arrays
function addVectors(a, b) {
   if (a.length !== b.length) {
       throw new Error("Vector arrays must be the same length to add them");
   }
   return a.map(function(item, index) {
       return item += b[index];
   });
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Are you sure you want to do it without the loop? Ok well:

a.forEach(function(currentElement, Index){
    b[Index] += currentElement;
});