1

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?

Muirik
  • 6,049
  • 7
  • 58
  • 116

3 Answers3

3

you can use .map() to get an array of ids and use Set to dedupe it :

const data = [{
    firstName: "John",
    lastName: "Johnson",
    _id: 23
  },
  {
    firstName: "John",
    lastName: "Johnson",
    _id: 23
  },
  {
    firstName: "Mary",
    lastName: "Smith",
    _id: 24
  }
]

const result = [... new Set(data.map(({_id}) => _id))]

console.log(result.length)
Taki
  • 17,320
  • 4
  • 26
  • 47
3

Another option is using reduce to summarise the array into an object using the _id as the key. Use Object.values to convert back the object into an array.

var arr = [{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"Mary","lastName":"Smith","_id":24}]

var result = Object.values(arr.reduce((c, v) => Object.assign(c, {[v._id]:v}), {}));

console.log(result.length);

Another option is using new Set and size property

var arr = [{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"Mary","lastName":"Smith","_id":24}]

var result = new Set(arr.map(o => o._id)).size;

console.log(result);
Eddie
  • 26,593
  • 6
  • 36
  • 58
1

Get all the _id from your array of object using map() and use Set to find unique _id and finally use size to get how many of ids are unique?

  1. The Set object lets you store unique values of any type

  2. The map() method creates a new array with the results of calling a provided function on every element in the calling array

var obj = [{
    "firstName": "John",
    "lastName": "Johnson",
    "_id": 23
  },
  {
    "firstName": "John",
    "lastName": "Johnson",
    "_id": 23
  },
  {
    "firstName": "Mary",
    "lastName": "Smith",
    "_id": 24
  }
];

function countUnique(iterable) {
  return new Set(iterable).size;
}

finalArray = obj.map(function(obj) {
  return obj._id;
});

console.log(countUnique(finalArray));
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103