How to merge two arrays?
jolamemushaj
Posted on September 15, 2022
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']
💖 💪 🙅 🚩
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 Simplify, Groupify, Conquer: The convenience of Object.GroupBy() in JavaScript
December 17, 2023