javascriptarrays

Checking if the array has duplicates apart from one element Javascript Dice


I'm struggling to implement a function to simply check if an array has all the same numbers apart from one.

I have tried a few methods now and I feel like I'm getting nowhere. The reason for this is for a dice game the user can select a number of dices and then roll and score bonus points for duplicate numbers and other sequences etc..

I thought it would be simple to check if the array had all duplicates apart from one element in the array but i cant get it to work.

I was thinking of something like check the elements in the array and see if the all the elements are the same value apart from one by using something with the array.length-1.

Examples dice values which would be true:

[1,2,2,2] or [4,4,2,4] (for 4 dice) //true
[1,1,6] (for 3 dice )//true

I tried something like this :

function countDuplicate(array) {
  var count = 0;
  var sorted_array = array.sort();

  for (let i = 1; i < sorted_array.length; i++)
  {
    if (sorted_array[i] == sorted_array[i+1]) {
        count += count;
    }
  }

  if (count === sorted_array.length-1) {
    return true;
  }

  return false;
}

But it doesn't seem to work.

Hope this is enough sorry I'm new to Javascript and Stackoverflow.


Solution

  • One way to implement this is to build an array of counts of each of the values in the array. This list can then be checked to ensure its length is 2 and the minimum count is 1:

    const countDuplicate = (array) => {
      let counts = Object.values(array.reduce((c, v) =>
        (c[v] = (c[v] || 0) + 1, c), {}));
      return counts.length == 2 && Math.min(...counts) == 1
    }
    
    console.log(countDuplicate([1,2,2,2]));
    console.log(countDuplicate([4,4,2,4]));
    console.log(countDuplicate([1,1,6]));
    console.log(countDuplicate([2,2,4,4]));
    console.log(countDuplicate([1,2]));