DEV Community

Cover image for 1 line of code: How to merge two Arrays and clean all duplicate entries
Martin Krause
Martin Krause

Posted on

1 line of code: How to merge two Arrays and clean all duplicate entries

const mergeArrayUnique = (a, b) => [ Set([...a, ...b])];
Enter fullscreen mode Exit fullscreen mode

Returns a new Array which contains all the values of the two Arrays. Ensures that the new array contains only unique values. Works only for primitive values (string, number, bigint, boolean, undefined, symbol, and null).

javascript #webdev #productivity #codequality

The repository & npm package

You can find the all the utility functions from this series at
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.

Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash

Top comments (3)

drstrangelug profile image
Paul Loveridge

The code is very efficient but I would not use it in a professional environment without a comment explaining what it does. Less experienced team members may well look at that and not understand what is doing.

It's not efficient if the developer that comes after you takes twenty minutes to figure out what the heck is going on.

igorfilippov3 profile image
Ihor Filippov

This will only work with primitives. With more complicated cases, like array of objects, it will not work

martinkr profile image
Martin Krause

Hi Igor,

thank you for your contribution, yes exactly, it's leveraging the set object. It's not doing a deep comparison.
I will update the description to be more precise.