Using ES6 JavaScript - spread syntax:
const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = [...a, ...b]; // c = ['a', 'b', 'c', 'd', 'e', 'f']
It is also the fastest way to concatenate arrays in JavaScript today.
However, when dealing with large arrays, it is more efficient to chain them (concatenate logically):
function chainArrays<T>(...arr: T[][]): Iterable<T> {
return {
[Symbol.iterator](): Iterator<T> {
let i = 0, k = -1, a: T[] = [];
return {
next(): IteratorResult<T> {
while (i === a.length) {
if (++k === arr.length) {
return {done: true, value: undefined};
}
a = arr[k];
i = 0;
}
return {value: a[i++], done: false};
}
};
}
}
}
// usage example:
const a = [1, 2];
const b = [3, 4];
const c = [5, 6];
for (const value of chainArrays(a, b, c)) {
console.log(value); //=> 1, 2, 3, 4, 5, 6
}
Above, we have to use while(i === a.length) logic in order to skip all empty arrays, while also for jumping to the next array at the end of the current one.
A generator approach for the same is much simpler, while also slower:
function* chainArrays<T>(...arr: T[][]) {
for (const i of arr)
for (const v of i)
yield v;
}
// test:
for (const value of chainArrays(a, b, c)) {
console.log(value); //=> 1, 2, 3, 4, 5, 6
}
Internally, a generator is translated into a more verbose IterableIterator, which used to perform slower than a manual iterable, but JavaScript engines keep improving, so it's for you to test it out in your environment ;) But I tested it under Node v20, and on average the manual iterable performs 2 times faster than our generator here.
For a complete TypeScript implementation (including reversed logic), see this gist, or this repo.