How to Flatten a 2-D array in JavaScript ?

You can flatten a 2-D array in JavaScript using the concat and apply method as shown in the below code snippet.

The first step is to merge the 2-D array in to 1-D array using the concat method and then use the apply method to flatten it by passing the array of arguments.

How to Flatten a 2-D array in JavaScript ?

var programminglanguages = [];
programminglanguages[0] = ['C#', 'VB.NET'];
programminglanguages[1] = ['F#', 'Java', 'Oxygene.NET'];
var flattenedArray = programminglanguages.concat.apply([], programminglanguages);
console.log(flattenedArray);

image

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply