Search code examples
javascriptrecursioncountletter

JavaScript Count Duplicate Letter Recursively


I face a problem while coding. I want to count how many letters in a word repeat recursively. My code looks like this :

var check = words[0]

  if(!words){
     return 0
  } else {
     for(var i = 0; i < words.length; i++){
        if(words[i] == check){
           return 1 //+ countDuplicate (words.slice(1))
        }
     }
     return countDuplicate (words.slice(1))
  }

example for test case :

countDuplicate ('greatestme') // 2, ==> which are 'e' 3 times and 't' 2 times

Solution

  • /* Method 1 */
    function countDuplicate1(word) {
      var arr = word.split("").reduce((acc, cv) => {
        if(!acc[cv]) {
          acc[cv] = 1;
        } else {
          acc[cv]++;
        }
        return acc;
      }, {});
      return Object.values(arr).filter(val => val >1).length;
    }
    
    /* Method 2 */
    function countDuplicate2(word) {
      var arr = [];
      for(var i=0; i< word.length; i++) {
        var chr = word[i];
        for(var j=i+1; j< word.length; j++) {
          if((word[j] == chr) && !arr.includes(word[j])) {
            arr.push(word[j]);
          }
        }
      }
      return arr.length;
    }
    var count1 = countDuplicate1('greatestme');
    var count2 = countDuplicate2('greatestme');
    console.log(count1);
    console.log(count2);

    See if this helps.