r/javascript • • Mar 02 '19

Useful javascript one-liners.

https://medium.com/@smellycode/js-one-liners-8bc0a6af2345?source=friends_link&sk=a9295a05aef9e514e137fca7eeb89cd1
344 Upvotes

96 comments sorted by

View all comments

Show parent comments

1

u/smellycode Mar 02 '19

Well, you need to define the definition of duplicates. :)

const a = {a: 'A'};
const b = a;
const c = {...a};
const array = [a, b]; // contains duplicate. a and b are duplicates.
const array = [a, c]; // does not contain duplicate. a and c are two different objects, albeit they have the same structure.

-1

u/Pavlo100 Mar 02 '19

duplicates are when they have the same structure, a and c is a very normal use case, in this case you would like to remove c

2

u/smellycode Mar 02 '19

if that is the case then this might help.

const removeDuplicates = 
    arr => arr.filter((item, index) => 
        index === arr.findIndex(v => isEqual(v, item)));

isEqual can be your own or 3rd party comparator function. Here's one naive implementation

const isEqual = (a, b) => 
    typeof a === 'object' && typeof b === 'object' 
        ? JSON.stringify(a) === JSON.stringify(b) : a === b;

Hope this helps.

0

u/Pavlo100 Mar 02 '19
JSON.stringify({identifier: 5, version: 2}) === JSON.stringify({version: 5, identifier: 2})
// false

Same structure, different order

All i am saying is that you should specify what the function works on.

The function works great on strings and numbers.

2

u/smellycode Mar 02 '19

I didn't know that the order of keys matters when we stringify. Thanks for pointing it out.