Is there a short way / best practice to concat 3 arrays into 1 array ?
var arr = [],
arr1 = [ 1 , 2 , 3 ],
arr2 = [ 4 , 5 , 6 ],
arr3 = [ 7 , 8 , 9 ];
arr = arr.concat(arr1);
arr = arr.concat(arr2);
arr = arr.concat(arr3);
The shortest (and fastest) solution is arr = arr1.concat(arr2, arr3);
Alternatives:
arr = arr.concat(arr1, arr2, arr3)arr = Array.prototype.concat(arr1, arr2, arr3)arr = [].concat(arr1, arr2, arr3)arr = arr1.concat(arr2,arr3)Spread syntax makes concatenation easy:
arr = [...arr1, ...arr2, ...arr3]
You can even include non-array items inline:
arr = [...arr1, 42, ...arr2, ...arr3]
There's not much to be done. You can simplify it:
arr = arr.concat(arr1).concat(arr2).concat(arr3)
Or see @Radko Dinev answer for an even simpler (and better) way to do it.
If you have an array of arrays (with a variable number of arrays), you can try:
var m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var new_m = [];
new_m.concat.apply(new_m, m);
_.reduce(arrays, function(result, arr) {
return result.concat(arr)
}, [])
Array.reduce method for this purpose.If you are here in 2022, there are 3 solutions (with short syntax), a b c are arrays :
let x = [].concat(a, b, c);
let y = [...a, ...b, ...c];
let z = [a, b, c].flat();
Following benchmark :
z is the worst by far.
y is faster with small arrays, but x faster with largest arrays.
With small arrays, it's always fast.
So, we should take the fastest answer with largest arrays : x
arr1+arr2+arr3toconcat