Reputation: 11
Could someone please look over my code and explain why my return value = 3 when it should be 2? The object has the correct count {1: 2, 2: 3, 3: 1, 4: 1, 5: 1}. Only two values are >= 2.
function countDuplicates(arr) {
let dupNums = {};
let count = 0;
for (let i=0; i<arr.length; i++) {
if (dupNums[arr[i]] === undefined) {
dupNums[arr[i]] = 0;
}
if (dupNums[arr[i]] !== undefined) {
dupNums[arr[i]] += 1;
}
if (dupNums[arr[i]] >= 2) {
count++;
}
}
return count;
}
console.log(countDuplicates([1,2,1,3,2,4,5,2]));
Upvotes: 0
Views: 63
Reputation: 11001
Use one Set
to track dup nums and another Set
for tracking count.
Following should work for you scenario.
function countDuplicates(arr) {
const dupNums = new Set();
const countSet = new Set();
arr.forEach((num) =>
dupNums.has(num) ? countSet.add(num) : dupNums.add(num)
);
return countSet.size;
}
console.log(countDuplicates([1, 2, 1, 3, 2, 4, 5, 2]));
Upvotes: 1
Reputation: 370679
You have three 2s and two 1s. Each time a duplicate is found, count
gets incremented.
Iterate over the values of the object afterwards instead, and count up the number of values which are >= 2:
function countDuplicates(arr) {
const dupNums = {};
for (const num of arr) {
dupNums[num] = (dupNums[num] || 0) + 1;
};
return Object.values(dupNums)
.filter(num => num >= 2)
.length;
}
console.log(countDuplicates([1, 2, 1, 3, 2, 4, 5, 2]));
or with reduce
:
function countDuplicates(arr) {
const dupNums = {};
for (const num of arr) {
dupNums[num] = (dupNums[num] || 0) + 1;
};
return Object.values(dupNums)
.reduce((a, num) => a + (num >= 2), 0)
}
console.log(countDuplicates([1, 2, 1, 3, 2, 4, 5, 2]));
Upvotes: 1