Say I have two arrays:
[[1], [2], [3], [4], [5]]
[[1], [2], [1], [3], [4]]
I want to add each value to make:
[[2], [4], [4], [7], [9]]
What would be the best way to do this?
Say I have two arrays:
[[1], [2], [3], [4], [5]]
[[1], [2], [1], [3], [4]]
I want to add each value to make:
[[2], [4], [4], [7], [9]]
What would be the best way to do this?
You could loop through items in array and create your result array on the go.
var firstArray = [[1], [2], [3], [4], [5]];
var secondArray = [[1], [2], [1], [3], [4]];
var thirdArray = [];
firstArray.forEach(function(ele, index){
thirdArray.push([ele[0] + secondArray[index][0]])
});
Like this:
var res = [];
for(var i=0;i<arr1.length;++i)
{
for(var j=0;j<arr1.length;++j)
res.push((arr1[i] + arr2[j]));
}
return res;
Can be done using map
like so (demo)
var a = [[1], [2], [3], [4], [5]];
var b = [[1], [2], [1], [3], [4]];
var result = a.map(function(value, index){
return [a[index][0] + b[index][0]];
});
console.log(result);
output
[ [ 2 ], [ 4 ], [ 4 ], [ 7 ], [ 9 ] ]
Online Demo - https://repl.it/CacI/1
You can use a .forEeach() or .map().
The main differences to notice in this example:
.map()
returns a new Array of objects created by taking some action on the original item.
.forEach()
returns nothing, it just iterates the Array performing a given action for each item.
Example using .forEach():
var data1 = [[1], [2], [3], [4], [5]],
data2 = [[1], [2], [1], [3], [4]],
result = [];
data1.forEach(function(item, index){
result.push([item[0] + data2[index][0]]);
});
console.log(result);
// result = [[2], [4], [4], [7], [9]]
Example using .map():
var data1 = [[1], [2], [3], [4], [5]],
data2 = [[1], [2], [1], [3], [4]],
result;
result = data1.map(function(currentValue, i){
return [data1[i][0] + data2[i][0]];
});
console.log(result);
// result = [[2], [4], [4], [7], [9]]
You can use a forEach
loop on one of the two arrays and do it like this:
var arr1 = [[1], [2], [3], [4], [5]];
var arr2 = [[1], [2], [1], [3], [4]];
var sum = [];
arr1.forEach(function(e,i){
sum.push([e[0]+arr2[i][0]]);
console.log(sum[i]);
});