60

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?
}
Anderson Green
  • 30,230
  • 67
  • 195
  • 328

6 Answers6

156

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);
Blaž Zupančič
  • 2,176
  • 2
  • 13
  • 22
  • the underscore way gives me an error when I try to use it on something simple, says that it is undefince – AlThePal78 Oct 06 '17 at 15:43
  • 5
    @daddycardona underscore.js is an external library. It will be undefined till you import it. http://underscorejs.org – Blaž Zupančič Oct 09 '17 at 13:17
  • 3
    Just Complementing... ES2019 introduced the .flat() method in Array Prototype. You can pass "depth" paramter in flat() method to specify how deep a nested array structure should be flattened. Defaults to 1. – Lucas Simões Jan 04 '22 at 00:35
44

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);
Marty
  • 39,033
  • 19
  • 93
  • 162
31

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

Anand G
  • 3,130
  • 1
  • 22
  • 28
blvz
  • 1,335
  • 13
  • 15
14

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/

marteljn
  • 6,446
  • 3
  • 30
  • 43
  • What happens if the nested elements are objects rather than numbers or strings? – Marty Feb 12 '13 at 02:07
  • @MartyWallace `["0", "0", "1", "2", "3", "3", "4", "4", "5", "[object Object]"]` This is what happens. I see your point my solution will only work with strings and numbers. – marteljn Feb 12 '13 at 02:09
1
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];
});
Alan Wells
  • 30,746
  • 15
  • 104
  • 152
Balasubramanian
  • 5,274
  • 6
  • 33
  • 62
0
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))

http://jsfiddle.net/Saturnix/ReeqQ/

Saturnix
  • 10,130
  • 17
  • 64
  • 120