Merge two arrays without duplicates in JavaScript

20 September 2018   0 comments   Javascript

Here's how you do it if you don't care about the order:

const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
console.log([ Set([...array1, ...array2])]);
// prints [1, 2, 3, 4]

It merges two arrays first. Then it creates a set out of that merged array and lastly convers the set back out to an array.

I searched for a solution and all I found was dated or wrong. This oneliner works and I'm using it to make it possible to add a list of product versions to another list and I don't want to mutate existing arrays because of React state stuff.

If you want to see the ES5 version, check out this Babel repl.


Your email will never ever be published

Related posts

A darn good search filter function in JavaScript 12 September 2018
Comparing KeyCDN and DigitalOcean's new Spaces CDN 28 September 2018
Related by Keyword:
React.memo instead of React.PureComponent 02 November 2018
Fastest way to uniquify a list in Python >=3.6 23 December 2017
Don't forget your sets in Python! 10 March 2017
Associative arrays 21 March 2007
Fastest way to uniqify a list in Python 14 August 2006