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([...new 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.
- Comparing KeyCDN and DigitalOcean's new Spaces CDN 28 September 2018
- Related by category:
- Related by keyword:
- Fastest way to uniqify a list in Python 14 August 2006
- Fastest way to uniquify a list in Python >=3.6 23 December 2017
- React.memo instead of React.PureComponent 02 November 2018
- Don't forget your sets in Python! 10 March 2017
- Associative arrays 21 March 2007