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?
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))
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]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.