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

跟風遠走 提交于 2019-12-10 15:52:14

问题


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:


回答1:


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.




回答2:


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

_.uniqWith(clickables, _.isEqual)

It is suggested in the docs



来源:https://stackoverflow.com/questions/24591236/why-isnt-lodashs-unique-returning-unique-objects-when-i-pluck-a-field-that-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!