Arash Howaida
Arash Howaida

Reputation: 2617

concat arrays with forEach

I have two arrays that are made up of 20 arrays of objects. Like this:

var array1 = [
  [
    {'x':0,'y':0},
    {'x':0,'y':0}
  ],
  [
    {'x':1,'y':1},
    {'x':1,'y':1}
  ],
...
  [
    {'x':19,'y':19},
    {'x':19,'y':19}
  ]
];

var array2 = [
  [
    {'x':0,'y':0},
    {'x':0,'y':0}
  ],
  [
    {'x':1,'y':1},
    {'x':1,'y':1}
  ],
...
  [
    {'x':19,'y':19},
    {'x':19,'y':19}
  ]
];

I want the end result to be:

[
    [
    {'x':0,'y':0},
    {'x':0,'y':0},
    {'x':0,'y':0},
    {'x':0,'y':0}
    ],
...
];

So I'm attaching two items in each array, meaning each array should contain four objects now.

What I tried was:

      var array3 = array1;

      array3.forEach(function(item,i) {
         item.concat(array2[i])
      })

But nothing was appended

Question

Is there a less painstaking approach to concat items iteratively?

Upvotes: 8

Views: 10217

Answers (4)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

Array.concat() is not mutating the original array which means it creates a new instance of array.

Therefore, you need to assign concatenated array to the original value.

  var array3 = array1;

  // If you don't want to mutate 'array1, use spread operator like following:
  // var array3 = [...array1];

  array3.forEach(function(item,i) {
     array3[i] = item.concat(array2[i])
  })

Upvotes: 9

adiga
adiga

Reputation: 35222

If you assign var array3 = array1 and mutate array3, it will change array1 as well because they are both referencing the same array.

You could map the first array and concat each inner array based with that of array2 based on the index

const array3 = array1.map((o, i) => o.concat(array2[i]))

or in ES5:

var array3 = array1.map(function(o, i) {
  return o.concat(array2[i])
})

const array1=[[{x:0,y:0},{x:0,y:0}],[{x:1,y:1},{x:1,y:1}],[{x:19,y:19},{x:19,y:19}]],
    array2=[[{x:0,y:0},{x:0,y:0}],[{x:1,y:1},{x:1,y:1}],[{x:19,y:19},{x:19,y:19}]];

const array3 = array1.map((o, i) => o.concat(array2[i]))

console.log(array3)

Upvotes: 5

Jamiec
Jamiec

Reputation: 136104

This is a fairly typical "zip" operation, can can be accomplished using map.

var array1 = [
  [
    {'x':0,'y':0},
    {'x':0,'y':0}
  ],
  [
    {'x':1,'y':1},
    {'x':1,'y':1}
  ],
  [
    {'x':19,'y':19},
    {'x':19,'y':19}
  ]
];

var array2 = [
  [
    {'x':0,'y':0},
    {'x':0,'y':0}
  ],
  [
    {'x':1,'y':1},
    {'x':1,'y':1}
  ],
  [
    {'x':19,'y':19},
    {'x':19,'y':19}
  ]
];

var result = array1.map( (item,i) => item.concat(array2[i]));
console.log(result);

Upvotes: 11

Christopher Janzon
Christopher Janzon

Reputation: 1039

How about this?

var array3 = array1.map((a, idx) => [...a, ...array2[idx]] )

Upvotes: 5

Related Questions