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?
}
6 Answers 6
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);
3 Comments
How about:
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
function get1DArray(arr){
return arr.join().split(",");
}
console.log(get1DArray(arrToConvert));
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var modifiedArray = arrToConvert.map(function(array){
return array[0]+array[1]+array[2];
});
Another Example
var passengers = [
["Thomas", "Meeks"],
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"]
];
var modifiedNames = passengers.map(function(convArray){
return convArray[0]+" "+convArray[1];
});
Comments
var arrToConvert = [[0, 0, 1], [2, 3, 3], [4, 4, 5]];
function get1DArray(arr){
var result = new Array();
for (var x = 0; x < arr.length; x++){
for (var y = 0; y < arr[x].length; y++){
result.push(arr[x][y])
}
}
return result
}
alert (get1DArray(arrToConvert))
Array.join()? developer.mozilla.org/en-US/docs/JavaScript/Reference/…Array.join()returns a string instead of an array.arrToConvert.flat()?['a', 'b', 'c', 'd', ['a', 'b', 'c']]to['a', 'b', 'c', 'd', 'a', 'b', 'c']