Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 369
Arash Howaida Avatar asked Aug 07 '19 09:08

Arash Howaida


People also ask

How to combine two arrays into one?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How to concat 2 arrays in js?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do I merge two arrays in typescript without duplicates?

Example 1: Using concat() and for Loop In the above program, the two array elements are merged together and the duplicate elements are removed. Here, The two arrays are merged using the concat() method. The for...of loop is used to loop through all the elements of arr .


1 Answers

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);
like image 112
Jamiec Avatar answered Sep 18 '22 13:09

Jamiec