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);
@MuhammadHaseebKhan: no, you can't do that in JavaScript. This will convert the three arrays to strings (calling . join(',') on each array) and concatenate the three strings. But, for example, you can use the plus operator in PHP to concatenate arrays.
concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
4.3. The one remaining operator that can be applied to one-dimensional arrays is the concatenation operator (“&”), which joins two array values end to end.
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)
I would use _.flatten
.
var arr = [[1,2,3], [4,5,6], [7,8,9]];
var result = _.flatten(arr) // [1,2,3,4,5,6,7,8,9]
Spread syntax makes concatenation easy:
arr = [...arr1, ...arr2, ...arr3]
You can even include non-array items inline:
arr = [...arr1, 42, ...arr2, ...arr3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With