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
CodePudding user response:
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 }
CodePudding user response:
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
orconst
instead ofvar
- 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'));