DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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) => [...new 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 github.com/martinkr/onelinecode
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)

Collapse
 
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.

Collapse
 
igorfilippov3 profile image
Igor Filippov

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

Collapse
 
martinkr profile image
martin krause Author

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.

Cheers!

⬇️ The only reason people scroll to the bottom...

...is because they want to read more. Create an account to bookmark, comment, and react to articles that interest you.