Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concat 3 arrays into 1 array in javascript / underscore

Tags:

javascript

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);
like image 878
Alon Avatar asked Feb 16 '14 12:02

Alon


People also ask

Can you concat 3 arrays in JavaScript?

@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.

How do I merge an array of arrays into a single array?

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.

Which symbol is used for array concatenation?

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.


3 Answers

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)
like image 70
Radko Dinev Avatar answered Oct 13 '22 14:10

Radko Dinev


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]
like image 29
sean Avatar answered Oct 13 '22 14:10

sean


Spread syntax makes concatenation easy:

arr = [...arr1, ...arr2, ...arr3]

You can even include non-array items inline:

arr = [...arr1, 42, ...arr2, ...arr3]
like image 31
Craig Gidney Avatar answered Oct 13 '22 14:10

Craig Gidney