Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, 4

The 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, 4

Without duplicates

Pass the result through a Set:

console.log([...new Set([...[1, 2], ...[2, 3]])].join(', '));

Output:

1, 2, 3

Adding 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, coffee

Common 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

Thanks for reading!

Donate to the site — we work hard for you.