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 ]
]
2

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use concat() function

a and b are you two arrays.

var c = a.concat(b);

console.log(c);

Comments

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);

3 Comments

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.
@RichardDunn it's an array of matrices, so you need to iterate and accumulate the concatenation at every iteration
Ah, my mistake, I thought the author was trying to merge two separate arrays. I need to read more carefully...
-1

You can use ES6 array spread operator

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

then just log it

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.