grateful
grateful

Reputation: 1128

merge unknown number of sub-arrays in array

I have an array like this:

arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]

and I want to turn it into an array like this:

arr = [  [x,x],[x,x] ,  [x,x],[x,x],[x,x],   [x,x]  ]

so I have tried this:

for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }

but it does not work. How can I 'merge' this intermediate level of array?

Upvotes: 3

Views: 3024

Answers (3)

Aaron Dunigan AtLee
Aaron Dunigan AtLee

Reputation: 2072

This is exactly what Array.prototype.flat() does.

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = arr.flat()
console.log(JSON.stringify(merged))

[["x","x"],["x","x"],["x","x"],["x","x"],["x","x"],["x","x"]]



Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122047

With ES6 you can use spread syntax with concat()

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = [].concat(...arr)
console.log(JSON.stringify(merged))

For older versions of ecmascript the same can be done using concat() and apply().

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = [].concat.apply([], arr)
console.log(JSON.stringify(merged))

Upvotes: 11

gen_Eric
gen_Eric

Reputation: 227260

The array.concat() doesn't change the array you call it on, but rather returns a new array - a new array you are ignoring.

You should create a result array and then append everything to that, instead of trying to modify arr.

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ];
var new_arr = [];

for(var i = 0; i < arr.length; i++){
    new_arr = new_arr.concat(arr[i]);
}

Upvotes: 1

Related Questions