0

Merge this array in javascript

const arr = [
    [ 1, '2', '6', 854301 ],
    [ 1, '2', '6', 854302 ],
    [ 1, '2', '6', 854303 ]
],
[
    [ 1, '3', '7', 854304 ],
    [ 1, '3', '7', 854305 ],
    [ 1, '3', '7', 854306 ]
]

I want this array output response as like below :

[
    [ 1, '2', '6', 854301 ],
    [ 1, '2', '6', 854302 ],
    [ 1, '2', '6', 854303 ],
    [ 1, '3', '7', 854304 ],
    [ 1, '3', '7', 854305 ],
    [ 1, '3', '7', 854306 ]
]
Karthik
  • 37
  • 2
  • 5
  • 1
    Hi! Welcome to StackOverflow! Please read our [tour](https://stackoverflow.com/tour) to get a better understanding about how to add a [*minimal*, *reproducible* example](https://stackoverflow.com/help/minimal-reproducible-example) – 0stone0 Dec 28 '20 at 19:20
  • Call [`Array.prototype.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) on the nested array. – Mr. Polywhirl Dec 28 '20 at 19:29

4 Answers4

4

You can simply use Array.prototype.flat() method.

const arr = [
  [
    [ 1, '2', '6', 854301 ],
    [ 1, '2', '6', 854302 ],
    [ 1, '2', '6', 854303 ]
  ],
  [
    [ 1, '3', '7', 854304 ],
    [ 1, '3', '7', 854305 ],
    [ 1, '3', '7', 854306 ]
  ]
];

const res = arr.flat();

console.log(res);
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
0

You can use .reduce:

const arr = [
  [
    [ 1, '2', '6', 854301 ],
    [ 1, '2', '6', 854302 ],
    [ 1, '2', '6', 854303 ]
  ],
  [
    [ 1, '3', '7', 854304 ],
    [ 1, '3', '7', 854305 ],
    [ 1, '3', '7', 854306 ]
  ]
];

const res = arr.reduce((acc,list) => acc.concat(list), []);

console.log(res);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 1
    Why are you putting the arrays into array just to reduce them into another array? `const arr3 = [...arr1, ...arr2];` or `const arr3 = arr1.concat(arr2)` would suffice. – Richard Dunn Dec 28 '20 at 19:25
  • @RichardDunn it's an array of matrices, so you need to iterate and accumulate the concatenation at every iteration – Majed Badawi Dec 28 '20 at 19:34
  • Ah, my mistake, I thought the author was trying to merge two separate arrays. I need to read more carefully... – Richard Dunn Dec 28 '20 at 19:42
0

You can use concat() function

a and b are you two arrays.

var c = a.concat(b);

console.log(c);
dev_mustafa
  • 1,042
  • 1
  • 4
  • 14
-1

You can use ES6 array spread operator

const array3 = [...array1, ...array2]

then just log it