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