How to merge two arrays
Short answer
Spread both arrays inside new square brackets:
const a = [1, 2];
const b = [3, 4];
console.log([...a, ...b].join(', '));Output:
1, 2, 3, 4The concat method
concat() does the same. Both approaches create a new array and leave the originals alone:
console.log([1, 2].concat([3, 4]).join(', '));Output:
1, 2, 3, 4Without duplicates
Pass the result through a Set:
console.log([...new Set([...[1, 2], ...[2, 3]])].join(', '));Output:
1, 2, 3Adding to an existing array
To add the elements of one array to another in place, use push() with ...:
const cart = ['tea'];
const more = ['cake', 'coffee'];
cart.push(...more);
console.log(cart.join(', '));Output:
tea, cake, coffeeCommon mistake
push() without ... adds the whole array as one nested element:
const cart = ['tea'];
cart.push(['cake', 'coffee']);
console.log(cart.length, JSON.stringify(cart));Output:
2 ["tea",["cake","coffee"]]Functions used in this recipe
- Array.prototype.concat — Merges arrays into a new array.
- Array.prototype.push — Appends elements to the end of an array.
- Set — A collection of unique values.