I have a unique array structure as follows:
const uniqueArray = [
{ _id: '1', userId: '5' },
{ _id: '2', userId: null },
{ _id: '3', userId: null },
{ _id: '4', userId: '1' },
{ _id: '5', userId: '2' },
{ _id: '6', userId: '4' },
{ _id: '7', userId: '4' },
{ _id: '8', userId: null },
{ _id: '9', userId: null },
{ _id: '10', userId: '2' }
];
I would like to find out the total number of unique userId values. If a value is null, each occurrence should be counted separately. If a non-null userId value is repeated, it should only be counted once.
I attempted the function below, but it does not consider null
values
const getUniqueCount = (arr, key) =>
arr.reduce(
(set, item) =>
set.add(typeof key === "string" ? item[key] : key(item)),
new Set()
).size;
getUniqueCount(uniqueArray, "userId");