0

What is the fastest way to make objectIds unique in an Array? For testing if 2 objectIds are equal, may I convert objectIds to other type, such as numbers or strings?

LiBook
  • 11
  • 2
  • Why wouldn't objectIds be unique? And yes, you can do `ObjectId.toString()` to get a unique string. – adeneo May 24 '15 at 14:30
  • @adeneo Because the objectIds I got are not from '_id'. And I got an very big array of objectIds after aggregation. ObjectIds are not unique in the array. – LiBook May 24 '15 at 14:38
  • Then a quick search should help you out -> http://stackoverflow.com/questions/1960473/unique-values-in-an-array – adeneo May 24 '15 at 14:58
  • Just remember to call to `toString` on the objects, otherwise comparison always fails as no two objects are ever the same – adeneo May 24 '15 at 14:59

1 Answers1

0

The easiest way would be to add the ids as keys of an object like this:

var array = [1, 2, 3, 4, 5, 6, 2, 3, 4]
var obj = {}
array.forEach(function(id){obj[id] = true})
array = Object.keys(obj)

Other alternatives would be sorting the array and using binary search and using some data structure like AVL tree.