[英]Using es6 spread to concat multiple arrays
我們都知道你可以做到:
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
但是你如何使這個動態連接 N 個數組呢?
一種選擇是使用reduce
:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);
當然,這是一個緩慢的解決方案(二次時間)。 或者,如果您可以使用 Lodash, _.flatten
可以完全滿足您的需求,並且效率更高(線性時間)。
編輯
或者,改編自 Xotic750 下面的評論,
[].concat(...arrs);
這應該是有效的(線性時間)。
另一種選擇可能是:
const nArrays = [ [1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11] ]; const flattened = [].concat(...nArrays); console.log(flattened)
let fruits = ["apples", "bananas", "pears"]; let vegetables = ["corn", "potatoes", "carrots"]; let produce = [...fruits, ...vegetables]; console.log(produce);
以下解決方案適用於我(ES6 中的擴展運算符):
let array = ['my','solution','works']; let newArray = []; let newArray2 = []; newArray.push(...array); //adding to same array newArray2.push([...array]); //adding as child/leaf/sub-array console.log(newArray); console.log(newArray2);
您不能單獨使用擴展語法來做到這一點,因為擴展語法要求您提前知道要連接的數組數量。 但是,您可以編寫以下函數:
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);
您可以在for..of
循環中使用 spread 元素將數組值連接到單個數組
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);
您可以使用遞歸函數和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]
你可以使用reduce
和Array.prototype.concat
做同樣的事情。 這類似於接受的答案,但在這種情況下不會無謂地使用傳播語法,其中x.concat(y)
是完全可以接受的(並且可能堆得更快)
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]
最好的選擇是使用 FlatMap,它可以幫助我們將多個數組合並為一個數組。
例子:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.flatMap(a => a);
結果將是
> (6) [1, 2, 3, 4, 5, 6]
快樂編碼...
我們可以通過以下方式使用es6解決
function mergeTwo(arr1, arr2) {
let result = [...arr1, ...arr2];
return result.sort((a,b) => a-b);
}
let arr1 = [1,2,3]; let arr2 = [3,4,5]; let arrs = [arr1, arr2].flat(); // [1,2,3,3,4,5] console.log(arrs);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.