Convert a 2D JavaScript array to a 1D array [duplicate]

Use the ES6 Spread Operator

arr1d = [].concat(...arr2d);

Note that this method is only works if arr2d has less than about 100 000 subarrays. If your array gets larger than that you will get a RangeError: too many function arguments.

For > ~100 000 rows

arr = [];
for (row of table) for (e of row) arr.push(e);

concat() is too slow in this case anyway.

The Underscore.js way

This will recursively flatten arrays of any depth (should also work for large arrays):

arr1d = _.flatten(arr2d);

If you only want to flatten it a single level, pass true as the 2nd argument.

A short < ES6 way

arr1d = [].concat.apply([], arr2d);

Leave a Comment