我们都知道你可以做:
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
但是,如何使它动态地连接N个数组?
我们都知道你可以做:
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);
应该是高效的(线性时间)。
Array.prototype.concat.apply([], arr)
。尽管这不再使用扩展运算符。 - Xotic750number[]
而不是 any[]
,则需要强制将空数组进行类型标注(例如:([] as number[]).concat(...arrs)
)。 - Simon_Weaver另一个选项可能是:
const nArrays = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11]
];
const flattened = [].concat(...nArrays);
console.log(flattened)
nArrays.flat()
。 - cayhorstmannlet fruits = ["apples", "bananas", "pears"];
let vegetables = ["corn", "potatoes", "carrots"];
let produce = [...fruits, ...vegetables];
console.log(produce);
最佳选择是使用FlatMap,它可以帮助我们将多个数组合并成一个单一的数组。
例子:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.flatMap(a => a);
结果将是:
> (6) [1, 2, 3, 4, 5, 6]
愉快编码...
以下方法对我有效(使用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);
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);
function concatN(...arguments) {
let accumulator = [];
for(let arg = 0; arg < arguments.length; arg = arg + 1) {
accumulator = [...accumulator, ...arguments[arg]];
}
return accumulator;
}
Array.prototype.concat
更好。您可以使用以下方式:[].concat(all, of, your, arrays);
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]
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);
concat
方法仍然可用... 建议翻译:为什么需要使用扩展运算符?concat
方法仍然可以使用... - Heretic MonkeyFunction.prototype.call.bind(Array.prototype.concat)
转换为ES5格式 :) - Yury Tarabanko