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 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
- Related by Text:
- jQuery and Highslide JS 08 January 2008
- I'm back! Peterbe.com has been renewed 05 June 2005
- Anti-McCain propaganda videos 12 August 2008
- Ever wondered how much $87 Billion is? 04 November 2003
- Guake, not Yakuake or Yeahconsole 23 January 2010