Reputation: 1837
I have these arrays:
// I want to calculate these arrays each other.
var a = [1,2,3]
var b = [1,2,3]
var c = [3,4,5]
// ->
var result = [5, 8, 11]
I can calculate two array with below method but how can I sum n arrays?
Array.prototype.Sum = function (arr) {
var s = [];
if (arr != null && this.length == arr.length) {
for (var i = 0; i < arr.length; i++) {
var c = this[i] + arr[i]
s.push(c);
}
}
return s;
}
Upvotes: 0
Views: 169
Reputation: 1690
With this function, you can sum several arrays and you don't need to "encapsulate" your arrays into another array...
Also, it works on old browsers.
function Sum(){
if (arguments.length == 0){
return null;
}
var s = arguments[0];
for(var j = 1; j < arguments.length; j++) {
var arr = arguments[j];
for (var i = 0; i < arr.length; i++) {
s[i] = s[i] + arr[i];
}
}
return s;
}
Just call Sum(a, b)
or Sum(a, b, c)
...
You can put it in your prototype too if you want (and make little changes to use this
if you want to sum in place).
Upvotes: 3
Reputation: 3387
A plain old ECMAScript 3 solution:
var arrays = [
[1, 2, 3],
[1, 2, 3],
[3, 4, 5]
];
function sum() {
var sum = [];
for(var i = 0; i < arguments.length; ++i) {
for(var j = 0; j < arguments[i].length; ++j)
sum[j] = (sum[j] || 0) + arguments[i][j];
} return sum;
}
sum.apply(this, arrays); // [ 5, 8, 11 ]
sum(arrays[0], arrays[1], arrays[2]); // [ 5, 8, 11 ]
Upvotes: 3
Reputation: 288120
Assuming
var arrays = [
[1,2,3],
[1,2,3],
[3,4,5]
];
Using your Sum
with EcmaScript 5 array methods,
var result = arrays.reduce(function(arr1, arr2){
return arr1.Sum(arr2);
});
Alternatively, consider not polluting Array.prototype
and just using something like (ES5)
var result = arrays.reduce(function(arr1, arr2) {
return arr1.map(function(num, index){
return num+arr2[index];
});
});
Or, simplifying using EcmaScript 6 arrow functions,
var result = arrays.reduce(
(arr1, arr2) => arr1.map(
(num, index) => num+arr2[index]
)
);
Upvotes: 5