Search code examples
javascriptarraysuniquelodashuniq

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


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"}

Solution

  • 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?