lodash uniq - choose which duplicate object to keep in array of objects

纵然是瞬间 提交于 2020-01-04 02:26:08

问题


is there any way to specify which array item to keep based on a key being non-empty. it seems uniq just keeps the first occurrence.

e.g:

var fruits = [
{'fruit': 'apples', 'location': '', 'quality': 'bad'}, 
{'fruit': 'apples', 'location': 'kitchen', 'quality': 'good'}, 
{'fruit': 'pears', 'location': 'kitchen', 'quality': 'excellent'}, 
{'fruit': 'oranges', 'location': 'kitchen', 'quality': ''}
];


console.log(_.uniq(fruits, 'fruit'));


/* output is:

Object { fruit="apples",  quality="bad",  location=""}
Object { fruit="pears",  location="kitchen",  quality="excellent"}
Object { fruit="oranges",  location="kitchen",  quality=""}

*/

Is there any way to tell lodash uniq to choose the duplicate that has a location value ? It's keeping the bad apples instead of the good apples.

~~~

My final solution was using sortByOrder inside uniq

console.log(_.uniq(_.sortByOrder(fruits, ['fruit','location'], ['asc','desc']),'fruit'))

resulted in:

Object { fruit="apples",  location="kitchen",  quality="good"}
Object { fruit="oranges",  location="kitchen",  quality=""}
Object { fruit="pears",  location="kitchen",  quality="excellent"}

回答1:


From what I see in docs at https://lodash.com/docs#uniq there is no way to specify that. Probably what you want to do is a groupBy fruit and then you can choose what quality you need. It depends on context and why you need it.

Can you explain your problem a little more?



来源:https://stackoverflow.com/questions/34687586/lodash-uniq-choose-which-duplicate-object-to-keep-in-array-of-objects

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