-3

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
egg
  • 165
  • 9

6 Answers6

3

Use map():

var a = [1,2,3,4,5],
    b = [1,2,3,4,5];

a.map(function(v, i) { return v + b[i] });

See MDN

haim770
  • 48,394
  • 7
  • 105
  • 133
1

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]])
});
lintu
  • 1,092
  • 11
  • 24
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – Brian Tompsett - 汤莱恩 Jul 11 '16 at 08:56
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;
MoustafaS
  • 1,991
  • 11
  • 20
0

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

Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
0

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]]
GibboK
  • 71,848
  • 143
  • 435
  • 658
0

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]);
});
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75