JavaScript: Get unique array elements of OBJECTS, remove duplicates in ONE-LINE code, yes!

David Kou
3 min readOct 12, 2019

This is an ancient question, a million years old. Why raising this antique question again?

When I browse StackOverflow today, this question pops up. As usual, the notorious StackOverflow admins soon marked it “on hold”, they even not take a moment to have a closer look! and the OP got -4 down-votes instantaneously. Oh my…

The question, in short, is to get the unique element in an array of objects (not primitives like integer), in addition, the object may not be exactly the same! Note the space highlighted in below snapshot!

I pondered a while and wish to come out a solution, but before that, I googled it, and found so many solutions:

Well there are so many solutions, but none of them works. Simple, “Nick ” is not regarded as “Nick”! Whaaaat? Yep, note the space in the tail!

I can definitely trim the space first and then use filter, map, loop, reduce … and other Vanilla Javascript to do that, but this is NOT what I want. I just hope to have a one line solution to get things done!

Using a library? Hmmmmm, Not an issue!

Here comes Lodash solutions:

If you run the code above, you find that it failed! The duplicate is still there!

I then came to give my favorite JavaScript library, ramda, a final shot! After trial and error, here comes the one-line solution!

Run the code here to see what happens!

How come? It is due to the magical R.eqProps ! It is smart and tolerant enough by allowing white spaces in comparing the props of two object. So considerate! It happens everyday, your teammate, the operators, whoever, never aware of such trailing spaces! Run the live code here!

If you want dig deep, here is the source code of R.eqProps!

Take this one-line solution, and now the world is silent and no twins in your array, finally!

R.uniqWith(R.eqProps, arrayWithDuplicates);

--

--