Skip to content
Advertisement

Correct result of amount of repeated values of array

I have written this code for detecting repetitive values of an array. But, it shows incorrect results, how to fix it?

  function RepeatedValues(str) {
 let repeatedCount = 0;
 const array = str.split("").slice().sort();

 for(var i = 0; i < array.length - 1; i++) { 
         if(array[i] == array[i + 1]) {
             ++repeatedCount;
             console.log(array[i] + ", " + repeatedCount);
         }
         else {
             repeatedCount = 0;
         }
     }
 
}

Output:

Result

Advertisement

Answer

Firstly, you do not log the result at the right place. Only once the next character has stopped being the same have you found all duplicates (aka. in your else block).

Next, your count starts at 0, so if you want to see r, 2 and you have counted 1 repetition, do repeatedCount + 1.

function RepeatedValues(str) {
  console.log(str)
  let repeatedCount = 0;
  const array = str.split("").slice().sort();

  for (var i = 0; i < array.length - 1; i++) {
    if (array[i] == array[i + 1]) {
      ++repeatedCount;
      continue;
    }

    if (repeatedCount > 0) {
      console.log(array[i] + ", " + (repeatedCount + 1));
    }

    repeatedCount = 0;
  }

  if (repeatedCount > 0) {
    console.log(array[i] + ", " + (repeatedCount + 1));
  }
}

RepeatedValues("bri2ghtwork2")
RepeatedValues("showreel")
RepeatedValues("circumstances")
RepeatedValues("Mississippi")

Note: I have taken the liberty of replacing your else block with a continue in the if block. In my opinion this makes the function easier to understand and ‘flatter’.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement