We all know you can do:
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
But how do you make this dynami
We can resolve using es6 following way
function mergeTwo(arr1, arr2) {
let result = [...arr1, ...arr2];
return result.sort((a,b) => a-b);
}
You could use a recursive function and 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]
You can do the same thing using reduce
and Array.prototype.concat
. This is similar to the accepted answer but doesn't senselessly use spread syntax where x.concat(y)
is perfectly acceptable (and likely heaps faster) in this case
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]
You can use spread element within for..of
loop to concatenate array values to a single array
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);
One option is to use reduce
:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);
Of course, this is a slow solution (quadratic time). Alternatively, if you can use Lodash, _.flatten
does exactly what you want, and does it more efficiently (linear time).
EDIT
Or, adapted from Xotic750's comment below,
[].concat(...arrs);
Which should be efficient (linear time).
Another option could be:
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);