Convert a 2D JavaScript array to a 1D array

Try .concat():

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


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

console.log(newArr);

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

How about:

var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];

function get1DArray(arr){
    return arr.join().split(",");
}

console.log(get1DArray(arrToConvert));

http://jsfiddle.net/JRR4J/


Try .reduce()

var test2d = [
  ["foo", "bar"],
  ["baz", "biz"]
];
var merged = test2d.reduce(function(prev, next) {
  return prev.concat(next);
});

console.log(merged)

Source: http://jsperf.com/2-dimensional-array-merge

Tags:

Javascript