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.

Comments

Your email will never ever be published.

Previous:
A darn good search filter function in JavaScript September 12, 2018 Web development, JavaScript
Next:
Comparing KeyCDN and DigitalOcean's new Spaces CDN September 28, 2018 Web development
Related by category:
How to SSG a Vite SPA April 26, 2025 JavaScript
Switching from Next.js to Vite + wouter July 28, 2023 JavaScript
An ideal pattern to combine React Router with TanStack Query November 18, 2024 JavaScript
get in JavaScript is the same as property in Python February 13, 2025 JavaScript
Related by keyword:
Fastest way to uniquify a list in Python >=3.6 December 23, 2017 Python
Fastest way to uniqify a list in Python August 14, 2006 Python
An effective and immutable way to turn two Python lists into one June 23, 2021 Python
React.memo instead of React.PureComponent November 2, 2018 React, JavaScript