0

I have an argument that passes me a 2D array and I want to get the numbers from that array and put them on a normal array.

The argument passed to me = ([1, 3, 2], [5, 2, 1, 4], [2, 1]) What I want to do = [1, 3, 2, 5, 2, 1, 4, 2, 1]

Thanks in advance, I think I'm having a brain fart over here!

hrmdev
  • 13
  • 6
  • 1
    [This](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) previous question should help – Ryan Walls Jan 17 '22 at 10:57
  • 5
    Does this answer your question? [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Expressingx Jan 17 '22 at 10:57

3 Answers3

2

You can use the flat method of Array!

const arr = [[1, 2, 3], [4, 5, 6]]

console.log(arr.flat()) 
// [1, 2, 3, 4, 5, 6]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

melvinb
  • 39
  • 4
1

Iterate the array and add all data in new array with concat() method.

var arr = [[1, 3, 2], [5, 2, 1, 4], [2, 1]];
var newArr = [];


for(var i = 0; i < arr.length; i++)
{
    newArr = newArr.concat(arr[i]);
}

console.log(newArr);
Faheem azaz Bhanej
  • 2,328
  • 3
  • 14
  • 29
1

You can use array flat method to convert 2d array to 1d array

const arr = [
      [1,2,3],
      [4,5,6]
    ].flat(1); //flat(depth:Number)

console.log(arr);

// [1,2,3,4,5,6]
Goutham J.M
  • 1,726
  • 12
  • 25