1

I have been asked to write a function that finds the total number of duplicate elements in any array. If an element shows up more than twice, I'm not sure how to stop the counter from incrementing.

ex) if input = [1,2,1,4,2,6,1], my output should be = 2

function countDuplicates(arr) {
  let counter = 0; 

  for (let outer = 0; outer < arr.length; outer++) {
    for (let inner = arr[outer + 1]; inner < arr.length; inner++) {

      if (arr[outer] === arr[inner]) {
        counter++;     
      }

    }
  }

  return counter; 
}

console.log(countDuplicates([1,2,1,4,2,6,1]));
2
  • can you try to add break; after the counter++; Commented Sep 20, 2020 at 5:32
  • I've tried, but it doesn't work for all tests. Commented Sep 20, 2020 at 23:24

3 Answers 3

5

You can put the duplicate elements into a Set and only increment when the element isn't already in the Set:

console.log(countDuplicates([1, 2, 1, 4, 2, 6, 1]));

function countDuplicates(arr) {
  let counter = 0;
  const found = new Set();
  const dupes = new Set();
  for (const item of arr) {
    if (dupes.has(item)) {
      continue;
    }
    if (found.has(item)) {
      dupes.add(item);
      counter++;
    }
    found.add(item);
  }
  return counter;
}

Another method, by counting frequencies of each item, then checking how many have occurred at least twice:

console.log(countDuplicates([1, 2, 1, 4, 2, 6, 1]));

function countDuplicates(arr) {
  const countsByItem = {};
  for (const item of arr) {
    countsByItem[item] = (countsByItem[item] || 0) + 1;
  }
  return Object.values(countsByItem)
    .filter(val => val >= 2)
    .length;
}

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

Comments

0

I would solve this by first obtaining the duplicated numbers when the first index of a number doesn't match with its last index. This giving us an array with all the duplicated numbers. And then with could filter them just to get the unique numbers of this array.

function countDuplicates(arr) {
  let duplicates = arr.filter((a, i) => arr.indexOf(a) !== arr.lastIndexOf(a))
  let filtered = duplicates.filter((a, i) => duplicates.indexOf(a) === i)

  return filtered.length;
}

let input = [1, 2, 1, 4, 2, 6, 1]
let res = countDuplicates(input)
console.log(res)

Comments

0

my way...

const Duplicates = arr =>
  {
  let count = 0
  new Set(arr).forEach(v=>{ count += (arr.filter(x=>x===v).length >1 ) ? 1 :0 })
  return count
  }

console.log ( Duplicates(  [1,2,1,4,2,6,1]) )

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.