My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Merging Two or More Arrays in JavaScript

Nathan's photo
Nathan
·Sep 11, 2021·

2 min read

There often comes a time in JavaScript when you need to combine two or more arrays.

I'll begin with a basic example, demonstrating how you can easily combine just two arrays into one:

const arrayOne = [1, 2, 3];

const arrayTwo = [4, 5, 6];

const mergedArray = arrayOne.concat(arrayTwo);

In this example, mergedArray will return [1, 2, 3, 4, 5, 6].

Merging multiple arrays

We can also use the concat() array method to merge more than two arrays together:

const arrayOne = [1, 2, 3];

const arrayTwo = [4, 5, 6];

const arrayThree = [7, 8 , 9];

const mergedArray = arrayOne.concat(arrayTwo, arrayThreee);

And in this example, mergedArray will return [1, 2, 3, 4, 5, 6, 7, 8, 9].

What's nice about concat() is that it uses a spread operator, so you can pass in as many parameters as you want, and they'll all get sequentially merged.

Removing duplicate values

Sometimes when merging arrays, you'll want to dispose of duplicate values.

Here's a quick snippet that'll do just that:

const arrayOne = [1, 2, 3, 4, 5];

const arrayTwo = [4, 5, 6, 1, 2];

let mergedArray = arrayOne.concat(arrayTwo);

mergedArray = mergedArray.filter((item, i) => mergedArray.indexOf(item) === i);

In this example, mergedArray will return [1, 2, 3, 4, 5, 6], the aggregate of arrayOne and arrayTwo in order and without any duplicates, as expected.

Conclusion

There's other ways to go about merging your arrays, but I've always found concat() to be the most practical.

I hope you enjoyed this quick little tutorial! Thanks for reading.