67

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?
}
asked Feb 12, 2013 at 1:58
5
  • Array.join()? developer.mozilla.org/en-US/docs/JavaScript/Reference/… Commented Feb 12, 2013 at 2:00
  • 1
    @MichaelBerkowski It looks like Array.join() returns a string instead of an array. Commented Feb 12, 2013 at 2:02
  • 1
    What is your expected output? Do you mean that you want the 3 sub-arrays flattened into one array? I misunderstood I think. Commented Feb 12, 2013 at 2:03
  • 9
    Isn't it simple as that arrToConvert.flat()? Commented Apr 21, 2021 at 20:13
  • How would you do this if some elements are arrays and some aren't. For example how would you convert ['a', 'b', 'c', 'd', ['a', 'b', 'c']] to ['a', 'b', 'c', 'd', 'a', 'b', 'c'] Commented Dec 4, 2023 at 15:26

6 Answers 6

172

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);
answered Oct 1, 2016 at 10:58
Sign up to request clarification or add additional context in comments.

3 Comments

the underscore way gives me an error when I try to use it on something simple, says that it is undefince
@daddycardona underscore.js is an external library. It will be undefined till you import it. underscorejs.org
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.
46

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);
answered Feb 12, 2013 at 2:00

Comments

34

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,2082 gold badges24 silver badges30 bronze badges
answered Oct 12, 2014 at 2:31

Comments

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/

answered Feb 12, 2013 at 2:06

2 Comments

What happens if the nested elements are objects rather than numbers or strings?
@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.
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
31.4k16 gold badges113 silver badges164 bronze badges
answered Feb 6, 2014 at 8:32

Comments

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/

answered Feb 12, 2013 at 2:19

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.