Why isn't lodash's _.unique returning unique objects when I pluck a field that is an object?
Asked Answered
F

3

5

I'm using lodash's _.unique and it's not working as expected. I'm doing this:

uniqueByFocusIndex = _.unique(clickables, false, "focusIndex");

And as you can see in the image (look at the right), it's returning two elements with the same values for their focusIndexes. I'd expect this to return one of the two, not both. Is it because _.unique only works on primitives and not objects?

Click to expand: enter image description here

Faradic answered 5/7, 2014 at 23:0 Comment(0)
C
9

_.uniqWith is what you might need so that you can do comparison using _.isEqual

_.uniqWith(clickables, _.isEqual)

It is suggested in the docs

Colloquialism answered 15/3, 2016 at 10:3 Comment(0)
S
5

It doesn't work because comparing objects is done by reference and returns false even if the objects' contents are the same.

Using a string for the callback will check those values using the pluck callback style, but comparison of those objects you have under that key will always be false.

I tried to find a way to do this with some other callback, but I think you would be better off just writing your own uniq function that fits your purposes.

Sheasheaf answered 6/7, 2014 at 0:0 Comment(2)
Yeah I think you're on to something. Check my answer for a solution, though.Faradic
@tieTYT I tried lots of different stuff to get it to work, but couldn't with how uniq is implemented. In your answer, even if you change one of the objects (x from 1 to 2) it still gives the same (now wrong) result.Sheasheaf
M
1

apparently for lodash version 4.x.x _.uniq works with primitives, If you want to work with array of json's the use _.uniqBy

uniqueByFocusIndex = _.uniqBy(clickables,"focusIndex");
Melvin answered 24/10, 2023 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.