Edgaras Karka
Edgaras Karka

Reputation: 7852

JS lodash uniq not woking with ObjectID list

I have a collection of mongoose models, I tried to use uniq lodash function to get unique id`s from the list, but still get the same list.

List elements are https://docs.mongodb.com/manual/reference/method/ObjectId/

const uniqueIds = uniq(ids) // not working

input:

[ 
  5c6f98ceb3f013291b497d82,
  5c6e447147c75d699f0514a1,
  5c6e447147c75d699f0514a1,
  5c6e447147c75d699f0514a1,
  5c6f98cfb3f013291b497d89,
  5c6f98cfb3f013291b497d89,
  5c6f98cfb3f013291b497d89,
  5c6f98cfb3f013291b497d89,
  5c6f98cfb3f013291b497d89,
  5c6f98cfb3f013291b497d89 
]

output:

    [ 
      5c6f98ceb3f013291b497d82,
      5c6e447147c75d699f0514a1,
      5c6e447147c75d699f0514a1,
      5c6e447147c75d699f0514a1,
      5c6f98cfb3f013291b497d89,
      5c6f98cfb3f013291b497d89,
      5c6f98cfb3f013291b497d89,
      5c6f98cfb3f013291b497d89,
      5c6f98cfb3f013291b497d89,
      5c6f98cfb3f013291b497d89
    ]

Upvotes: 1

Views: 1714

Answers (4)

Ambesh Tiwari
Ambesh Tiwari

Reputation: 756

this will work even for objectId arrays

 function onlyUnique(value, index, self) { 
      return self.indexOf(value) === index;
    }
    
    const uniqueArray=yourArray.filter(onlyUnique);

Upvotes: 0

DhanarajC
DhanarajC

Reputation: 21

Provided that the list is array, each element in the list is of the ObjectId, this should work. Each id in the list will be iterated and converted to sting for finding the unique elements

_.uniqBy(list, (id) => id.toString())

Upvotes: 2

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44685

The issue is that these are ObjectId objects, and probably a new one is generated for the same hash, so in that case, the references aren't the same the following will probably happen:

ObjectId("foo") == ObjectId("foo"); // false

In that case uniq() won't be able to recognize the same ObjectId. A solution would be to use uniqBy() to properly compare them, for example:

_.uniqBy(ids, id => id.valueOf());

Upvotes: 5

Ori Drori
Ori Drori

Reputation: 191976

Since the items are instances of ObjectId, you can't use _.uniq() because different object instances are always unique. You can use lodash's _.uniqBy(), with the str property of the object as the unique identifier:

_.uniqBy(list, 'str')

Upvotes: 1

Related Questions