How to merge two arrays?

jolamemushaj

jolamemushaj

Posted on September 15, 2022

How to merge two arrays?

Let’s say you have two arrays and want to merge them:

const firstTeam = ['Olivia', 'Emma', 'Mia']
const secondTeam = ['Oliver', 'Liam', 'Noah']
Enter fullscreen mode Exit fullscreen mode

One way to merge two arrays is to use concat() to concatenate the two arrays:

const total = firstTeam.concat(secondTeam)
Enter fullscreen mode Exit fullscreen mode

But since the 2015 Edition of the ECMAScript now you can also use spread to unpack the arrays into a new array:

const total = [...firstTeam, ...secondTeam]
console.log(total)
Enter fullscreen mode Exit fullscreen mode

The result would be:

// ['Olivia', 'Emma', 'Mia', 'Oliver', 'Liam', 'Noah']
Enter fullscreen mode Exit fullscreen mode

There is also another way, in case you don't want to create a new array but modify one of the existing arrays:

firstTeam.push(...secondTeam);
firstTeam; // ['Olivia', 'Emma', 'Mia', 'Oliver', 'Liam', 'Noah']
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
jolamemushaj
jolamemushaj

Posted on September 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Fundamentals: Arrays
javascript JavaScript Fundamentals: Arrays

December 29, 2022

How to merge two arrays?
javascript How to merge two arrays?

September 15, 2022

How JavaScript Works_01
javascript How JavaScript Works_01

November 2, 2021