0

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]));
1
  • 1
    because you count them more than once.... Commented Sep 22, 2020 at 3:21

2 Answers 2

1

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]));

Sign up to request clarification or add additional context in comments.

2 Comments

Note: IE does not support Object.values. Could use Object.keys otherwise
@AmitChigadani Note: Microsoft will end support for IE for most Microsoft online products in August of 2021. If you haven't started transitioning, now's the time. There are several polyfills for Object.values as well; see MDN.
1

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]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.