concat 3 arrays into 1 array in javascript / under

2020-06-08 05:30发布

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);

标签: javascript
6条回答
beautiful°
2楼-- · 2020-06-08 06:01

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]
查看更多
劳资没心,怎么记你
3楼-- · 2020-06-08 06:03

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);
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-06-08 06:11

A more flexible way:

var arraysToConcat = [arr1, arr2, arr3];
var arr = Array.prototype.concat.apply([], arraysToConcat);
查看更多
一夜七次
5楼-- · 2020-06-08 06:13

Spread syntax makes concatenation easy:

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

You can even include non-array items inline:

arr = [...arr1, 42, ...arr2, ...arr3]
查看更多
Ridiculous、
6楼-- · 2020-06-08 06:14
_.reduce(arrays, function(result, arr) {
    return result.concat(arr)
}, [])
查看更多
倾城 Initia
7楼-- · 2020-06-08 06:17

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)
查看更多
登录 后发表回答