Reputation: 217
I am splitting an array into two arrays arr1
& arr2
. Then I want to sum the values and bind into another array like arr3
. How can I do this?
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = [3,5,7,8]
this works fine with static arrays, but my problem is
var TotalOfArray = [];
var temparray = [];
for (i = 0, j = x.length; i < j; i += chunk) {
temparray = x.slice(i, i + chunk);
if (temparray.length == chunk) {
console.log("before loop: "+TotalOfArray.length);
if (TotalOfArray.length == 0) {
for (i in temparray) {
TotalOfArray[i] = temparray[i];
}
console.log("after loop: "+TotalOfArray.length);
} else {
for (i in temparray) {
TotalOfArray[i] = TotalOfArray[i] + temparray[i];
}
}
}
}
As you can see, x will be the main array which I am splicing into a temparray
array, so every time it will splice with array length 31 and than I want to do sum, chunk = 31 as of now. But it's not going into ELSE part.
Upvotes: 0
Views: 477
Reputation: 73918
If two arrays have equal length you can can use Array.prototype.map();
var data1 = [1,2,3,4],
data2 = [2,3,4,4],
result;
result = data1.map(function(value, i){
return value + data2[i];
});
console.log(result);
Upvotes: 1
Reputation: 18898
This is just a more simple version, that assumes equal lengths from both arrays. For a solution that works with variable length arrays, read further on.
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 4];
var arr3 = arr1.map(function(a, i) {
return a + arr2[i];
});
console.log(arr3);
This is going to be a more robust solution regardless. But it finds the array with the most values in it, and uses that for the map. Then, if undefined values are found in the other array, it will use 0 as the other number.
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 4, 5];
var sorted = [arr1, arr2].sort((a, b) => b.length - a.length);
var arr3 = sorted[0].map(function(a, i) {
return a + (sorted[1][i] || 0);
});
console.log(arr3);
Upvotes: 4
Reputation: 231
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = []
for (var i = 0; i < arr1.length; i++) {
arr3.push(arr1[i] + arr2[i])
}
Assuming arr1 and arr2 have the same length.
Upvotes: 0
Reputation: 27476
Use for
loop:
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = []
for (i in arr1) { arr3[i] = arr1[i] + arr2[i]; }
console.log(arr3)
Upvotes: 1