How to Create a Single Array from a Multidimensional Array in JavaScript?

Estimated read time 1 min read

You can create a single array from a multidimensional array in JavaScript using the flat() method. The flat() method takes an optional parameter for the depth to which it should flatten the array. If no depth is specified, the default is 1, which means that only one-level deep nested arrays are flattened. For example:

let multiArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let singleArray = multiArray.flat();
console.log(singleArray);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you have a deeper nested array, you can use a higher depth level:

let multiArray = [[1, 2, [3, 4]], [5, 6], [7, 8, 9]];
let singleArray = multiArray.flat(Infinity);
console.log(singleArray);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Note that the flat() method is only supported in modern browsers and in Node.js 12 and later. If you need to support older environments, you can write a custom function that flattens the array for you.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply