Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I want to convert a 2D JavaScript array to a 1D array, so that each element of the 2D array will be concatenated into a single 1D array.

Here, I'm trying to convert arrToConvert to a 1D array.

var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];  console.log(get1DArray(arrToConvert)); //print the converted array  function get1DArray(2dArr){     //concatenate each element of the input into a 1D array, and return the output     //what would be the best way to implement this function? } 
like image 935
Anderson Green Avatar asked Feb 12 '13 01:02

Anderson Green


People also ask

How do you make a 2D array into 1D?

Every row in your 2D array is placed end to end in your 1D array. i gives which row you are in, and j gives the column (how far into that row). so if you are in the ith row, you need to place i complete rows end to end, then append j more onto that to get your single array index.

Is 1D array faster than 2D?

Unless you are talking about static arrays, 1D is faster. Clearly the 2D case loses the cache locality and uses more memory. It also introduces an extra indirection (and thus an extra pointer to follow) but the first array has the overhead of calculating the indices so these even out more or less.

Why 2D array is better than 1D array?

The main difference between 1D and 2D array is that the 1D array represents multiple data items as a list while 2D array represents multiple data items as a table consisting of rows and columns. A variable is a memory location to store data of a specific type.


1 Answers

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); 
like image 135
Blaž Zupančič Avatar answered Nov 05 '22 14:11

Blaž Zupančič