Skip to content Skip to sidebar Skip to footer

Write A Javascript Function To Get The Number Of Occurrences Of Each Letter In Specified String

'Write a JavaScript function to get the number of occurrences of each letter in specified string.' I've tried this way, but all my outputs are 0 and I really don't get why. My id

Solution 1:

Two minor errors in your code.

  • Matching condition should be string1[i] == string1[i + 1]
  • Initiate counters with value 1 as each value will occur atleast one time.

functioncount(string) {
  let string1 = string.split("").sort().join("");
  let counter = 1;
  for (let i = 0; i < string.length; i++) {
    if (string1[i] == string1[i + 1]) {
      counter++;
    } else {
      console.log(string1[i] + " " + counter);
      counter = 1;
    }
  }
}
count("thequickbrownfoxjumpsoverthelazydog");

I would suggest you to use a different approach which will use .reduce and will return a nice object of the counts.

functioncount(string) {
  return string.split("").reduce(
    (acc, el) => {
      if(acc.hasOwnProperty(el))
        acc[el]++;
      else
        acc[el] = 1;
      return acc;
    }, {}
  )
}
var data = count("thequickbrownfoxjumpsoverthelazydog");
console.log(data);

Solution 2:

Use the function reduce to avoid the problem with only one occurence.

functioncount(string) {
  return string.split("").reduce((a, letter) => {
    a[letter] = (a[letter] || 0) + 1;
    return a;
  }, {});
}
console.log(count("thequickbrownfoxjumpsoverthelazydog"));
.as-console-wrapper { max-height: 100%!important; top: 0; }

Snippet with explanation

functioncount(string) {
  return string.split("").reduce((a, letter) => {
    var currentCount = a[letter];
    if (currentCount) { 
      currentCount = currentCount + 1; // If previously counted + 1
    } else {
      currentCount = 1; // Else initialize with first occurence.
    }
    
    a[letter] = currentCount; //Store the new count.return a;
  }, {});
}

console.log(count("thequickbrownfoxjumpsoverthelazydog"));

Resource

Solution 3:

Another approach I haven't seen here:

constcount = (str) => {
  let freq = {};
  for(let i = 0; i < str.length; i++) { // you can use for...of instead!const currentLetter = str.charAt(i);
    freq[currentLetter] = freq[currentLetter] + 1 || 1;
  }
  return freq;
}
console.log(count("thequickbrownfoxjumpsoverthelazydog"));
  1. Create empty object
  2. Assign a letter as a key and add + 1 to value OR set value to 1 if key doesn't exist.
  3. Return the object.

Solution 4:

You can do it like this

functioncount(text){
  var i = 0;
  var j = 0;
  var chars = newArray();
  var occurs = newArray();

  for(i = 0;i < text.length;i++){
    //save current char
    chars.push(text[i]);

    //get occurences
    occurs.push(countOccurs(text, text[i]));
  }

  //clean for duplicatesfor(i = 0;i < chars.length;i++){
    for(j = (i + 1);j < chars.length;j++){
      if(chars[i] == chars[j]){
        chars[j] = "";
        occurs[j] = 0;
      }
    }
  }

  //print it!for(i = 0;i < chars.length;i++){
    if(chars[i] != '')
      console.log("The char " + chars[i] + " appears " + occurs[i] + " times.");
  }
}

functioncountOccurs(text, character){
  var i = 0;
  var ret = 0;

  for(i = 0;i < text.length;i++)
    if(text[i] == character)
      ret++

  return ret;
}

count("abcdefabcd");

So you just count each char's occurs then clean the arrays.

Solution 5:

constcounterFunc = (string) => {
    let  counter = {};
    string.split('').map((char) => {
        if(typeof counter[char] !== 'undefined') {
            counter = {
                ...counter,
                [char]: counter[char] + 1
            }
        } else {
            counter[char] = 1
        }
    })

    returnObject.keys(counter).map( k => {
        return  k + counter[k];
    }).join('');
};

console.log(counterFunc("abcabcabcabcadftyeacrtfvcserfvaserdcvfrt"))

Post a Comment for "Write A Javascript Function To Get The Number Of Occurrences Of Each Letter In Specified String"