3

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?

2
  • How does that "not work"? What output does it give? Does it give any errors? Why are you starting with var i = 1? Commented Mar 31, 2017 at 14:14
  • Starting with i=1 because i=0 would be arr[0] to which I want to add the other sub-arrays. Commented Mar 31, 2017 at 14:16

3 Answers 3

11

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))

Sign up to request clarification or add additional context in comments.

2 Comments

Great! Just the kind of efficient code and new thing to learn I was looking for. What does dot dot dot (...) mean?
2

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"]]



Comments

1

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.