Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
How can I find out how many of each letter is in a given string?

So I want my code to count the amount of times a letter shows up within a string and output the result.

ie:

amount(door, o) ===> 2

Can I do it using a for loop using

function(amount,letter){
  var  count=0
  for (var i=0 ; i < amount.length ; i++) {
    if(amount[i] == letter[i]) count++
    }
  }

not really sure how to make it work

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your code was almost correct but there some mistakes

  • You have to give the function a name
  • You have to return count
  • You have to pass actual strings
  • You should use let or const instead of var
  • You should use === instead of ==

function amount(word, letter) {
  let count = 0;
  for (let i = 0; i < word.length; i++) {
    if(word[i] === letter) count++
  }
  return count;
}

console.log(amount('door', 'o'));

Using array methods you can simplify even more

function amount(word, letter) {
  return Array.prototype.reduce.call(word, (acc, el) => acc + (el === letter), 0);
}

console.log(amount('door', 'o'));

about 4 years ago · Juan Pablo Isaza Report

0

You can split the string into an array, then loop through each of the letters. We have a letterTracker object, which is where our values are stored. If the key of the letter doesn't exist in the object already, we'll add the key to it. If it does exist, we'll just add one to it.

var countLetters = (string)=>{
    const stringArr = string.split('')
    let letterTracker = {};
    stringArr.forEach(letter=>{
        letterTracker[letter]
            ? letterTracker[letter]++
            : letterTracker[letter] = 1
    });
    return letterTracker;
}

countLetters('wuddup'); //returns { w: 1, u: 2, d: 2, p: 1 }

Using a more ES5 friendly method, and without splitting the string into an array, we can do this (the same result will be achieved):

function countLetters(string){
    let letterTracker = {};
    for(let i = 0; i < string.length; i++){
        if(letterTracker[string[i]]){
            letterTracker[string[i]]++
        } else {
            letterTracker[string[i]] = 1
        }
    }
    return letterTracker;
}

countLetters('wuddupp?'); //returns { w: 1, u: 2, d: 2, p: 2, ?: 1 }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!