I need to loop through an array of objects and sum the total number of unique _id(s). Imagine a data structure that looks like this:
[
{ firstName: "John",
lastName: "Johnson",
_id: 23
},
{ firstName: "John",
lastName: "Johnson",
_id: 23
},
{ firstName: "Mary",
lastName: "Smith",
_id: 24
}
]
... for the above data set, my totalUniqueIDs
should be 2
.
If I were just looping through an array and getting the sum of "_id", I would do this:
let customersArray = docs.map(doc => doc._id);
let customersArrayLength = customersArray.length
console.log(customersArrayLength); // 3
This would of course give me 3 results.
How would I get just the sum of unique _id(s) in this situation? Do I first convert the array
to a set
, and then find the length
or size
?