DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Merging Two or More Arrays in JavaScript

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (2)

Collapse
queekusme profile image
Annie Kennedy

I dunno if there are any performance implications but I always do
[
…arr1,
…arr2
]

With the spread operator

Collapse
natclark profile image
Nathan Author

Interesting, I'm not sure what the performance implications would be. If I had time, I'd run a few quick tests to see!