DEV Community

jolamemushaj
jolamemushaj

Posted on

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

Top comments (4)

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

in python you can do the same thing with one line of the code:
array1 += array2

Collapse
 
ivan_jrmc profile image
Ivan Jeremic • Edited

In Js too lol.

[...arr1, ...arr2]

Collapse
 
jolamemushaj profile image
jolamemushaj

Image description

I tried but this was the result 😅

Collapse
 
topninja profile image
Michael • Edited

[...new Set([...arr1, ...arr2])] // ['Olivia', 'Emma', 'Mia', 'Liam', 'Noah']

to avoid duplicates