let phrase = prompt('Enter the phrase')
function letter(phrase) {
let frequency = {}
for(letter of phrase){
if(letter in frequency){
frequency[letter]
}
else{
frequency[letter]=1
}
}
return frequency
}
console.log(letter(phrase))
I want to have the result without the whitespaces. I have tried the split method but it then returns the count of the words not the letters.
CodePudding user response:
I want to have the result without the whitespaces.
If you want to check for a given condition (is the character a space) to perform a given action (ignore and continue) then what you're looking for is an if
statement:
let phrase = prompt('Enter the phrase')
function letter(phrase) {
let frequency = {}
for(letter of phrase){
// here
if (letter === ' ') {
continue;
}
if(letter in frequency){
frequency[letter]
}
else{
frequency[letter]=1
}
}
return frequency
}
console.log(letter(phrase))
There are a variety of ways to achieve the same end result. Alternate approaches could include:
- Wrap the loop body in an opposite condition (
if (letter !== ' '
) to conditionally perform the entire loop body - Remove all whitespace from the string before processing the loop
- Remove the whitespace property from the object after processing the loop
CodePudding user response:
here is an easy solution
let phrase = prompt('Enter the phrase')
function letter(phrase) {
phrase = phrase.replaceAll(" ","");
console.log(phrase)
let frequency = {}
for(letter of phrase){
if(letter in frequency){
frequency[letter]
}
else{
frequency[letter]=1
}
}
return frequency
}
console.log(letter(phrase))
CodePudding user response:
I added one line to your code:
let phrase = prompt('Enter the phrase')
function letter(phrase) {
let frequency = {}
for(letter of phrase)
{
if(letter != ' ') // added a check here for whitespace
{
if(letter in frequency)
{
frequency[letter]
}
else{
frequency[letter]=1
}
}
enter code here}
return frequency
}
console.log(letter(phrase))
CodePudding user response:
Hope this will work for you.
let phrase = prompt('Enter the phrase').replace(/\s/g, "");
function letter(phrase) {
let frequency = {}
for(letter of phrase){
if(letter in frequency){
frequency[letter]
}
else{
frequency[letter]=1
}
}
return frequency
}
console.log(letter(phrase))