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? }
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.
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.
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.
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
.
arr = []; for (row of table) for (e of row) arr.push(e);
concat()
is too slow in this case anyway.
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.
arr1d = [].concat.apply([], arr2d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With