Search code examples
lodashobjectid

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
    ]

Solution

  • 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());