简体   繁体   中英

concat 3 arrays into 1 array in javascript / underscore

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)

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]

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)
}, [])

Spread syntax makes concatenation easy:

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

You can even include non-array items inline:

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

A more flexible way:

var arraysToConcat = [arr1, arr2, arr3];
var arr = Array.prototype.concat.apply([], arraysToConcat);

If you are here in 2022, there are 3 solutions (with short syntax), abc 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM