Let’s say you have two arrays and want to merge them:
const firstTeam = ['Olivia', 'Emma', 'Mia']
const secondTeam = ['Oliver', 'Liam', 'Noah']
One way to merge two arrays is to use concat() to concatenate the two arrays:
const total = firstTeam.concat(secondTeam)
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)
The result would be:
// ['Olivia', 'Emma', 'Mia', 'Oliver', 'Liam', 'Noah']
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']
Top comments (4)
in python you can do the same thing with one line of the code:
array1 += array2
In Js too lol.
[...arr1, ...arr2]
I tried but this was the result 😅
[...new Set([...arr1, ...arr2])] // ['Olivia', 'Emma', 'Mia', 'Liam', 'Noah']
to avoid duplicates