2017-04-17 44 views
3

我們都知道,你可以做..ES6採用擴展到Concat的多個陣列

let arr1 = [1,2,3]; 
let arr2 = [3,4,5]; 
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5] 

但是,你怎麼做這個充滿活力的以Concat的ñ陣列? Thx

+0

您可以將動態數組存儲在數組中...... –

+0

或一個數組作爲值的對象。不可能迭代未知數量的個體變量 – charlietfl

+5

爲什麼你必須使用擴散算子? 'concat'方法仍然有效...... –

回答

6

一種選擇是使用reduce

let arrs = [[1, 2], [3, 4], [5, 6]]; 
arrs.reduce((a, b) => [...a, ...b], []); 

當然,這是一個緩慢的溶液(二次時間)。或者,如果您可以使用Lodash,則_.flatten完全符合您的要求,並且可以更有效地執行(線性時間)。

編輯

或者,改編自下面Xotic750的評論,

[].concat(...arrs); 

這應該是有效的(線性時間)。

+0

一個你有你的陣列在一個數組中,你可以。 'Array.prototype.concat.apply([],arr)'儘管這不再使用擴展運算符。 – Xotic750

+1

@ Xotic750不錯,但你可以使用擴散算子做到這一點!看我的編輯。 –

2

單獨使用擴展語法無法做到這一點,因爲擴展語法要求您知道預先連接了多少個數組。但是,您可以編寫以下功能:

function concatN(...arguments) { 
    let accumulator = []; 
    for(let arg = 0; arg < arguments.length; arg = arg + 1) { 
     accumulator = [...accumulator, ...arguments[arg]]; 
    } 
    return accumulator; 
} 

它可能不會是非常有效的,但(傳播語法的重複使用是O(N²))。使用Array.prototype.concat會更好。你可以這樣做:

[].concat(all, of, your, arrays); 
2

另一種選擇可能是:

const nArrays = [ 
 
    [1, 2, 3, 4, 5], 
 
    [6, 7, 8, 9], 
 
    [10, 11] 
 
]; 
 
const flattened = [].concat(...nArrays); 
 
console.log(flattened)

1

您可以使用for..of環內傳播元素來連接數組值到一個數組

let arr1 = [1,2,3]; 
 
let arr2 = [3,4,5]; 
 
let arr3 = []; 
 

 
for (let arr of [arr1, arr2 /* , arrN */]) arr3.push(...arr); 
 

 
console.log(arr3);

1

你可以使用一個遞歸函數和Array.prototype.concat

const concatN = (x,...xs) => 
 
    x === undefined ? [] : x.concat(concatN(...xs)) 
 

 
console.log(concatN([1,2,3], [4,5,6], [7,8,9])) 
 
// [1,2,3,4,5,6,7,8,9]

你可以使用reduceArray.prototype.concat同樣的事情。這是類似到接受的答案,但在這種情況下

const concatN = (...xs) => 
 
    xs.reduce((x,y) => x.concat(y), []) 
 

 
console.log(concatN([1,2,3], [4,5,6], [7,8,9])) 
 
// [1,2,3,4,5,6,7,8,9]

5

let fruits = ["apples", "bananas", "pears"]; 
 
let vegetables = ["corn", "potatoes", "carrots"]; 
 

 
let produce = [...fruits, ...vegetables]; 
 

 

 
console.log(produce);

不無謂使用傳播語法,其中 x.concat(y)是完全可以接受的(可能快堆)
+1

這個給定的代碼與給定的問題完全相同。這不是爲N個數組製作dynamiclly concat解決方案的答案。 –