Thursday, September 15, 2022
HomeWordPress DevelopmentMethods to merge two arrays?

Methods to merge two arrays?


Let’s say you’ve two arrays and need to merge them:

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

Exit fullscreen mode

One technique to merge two arrays is to make use of concat() to concatenate the 2 arrays:

const whole = firstTeam.concat(secondTeam)
Enter fullscreen mode

Exit fullscreen mode

However because the 2015 Version of the ECMAScript now you can even use unfold to unpack the arrays into a brand new array:

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

Exit fullscreen mode

The outcome can be:

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

Exit fullscreen mode

There may be additionally one other approach, in case you do not need to create a brand new array however modify one of many current arrays:

firstTeam.push(...secondTeam);
firstTeam; // ['Olivia', 'Emma', 'Mia', 'Oliver', 'Liam', 'Noah']
Enter fullscreen mode

Exit fullscreen mode

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments