1

This is the Code I have written to count

var name = "Interesting";
var letter_count = {};
 for(var i in name){
   if (!(i in letter_count)){
    letter_count[i] = 1;
   }
  else {
   letter_count[i] += 1;
  }
}
console.log(letter_count);

expected output: { i: 2, n:2, t:2, e:2, r:1 s:1, g:1 }

1
  • 1
    i represents the index of the letter in name, not the letter itself Commented Sep 21, 2018 at 16:33

4 Answers 4

4

The variable i in for...in represents the key (or index in the case of an array). Since you don't need the index, use for...of instead:

var name = "Interesting";
name = name.replace(/ +/g, "").toLowerCase();
// name = name.split('').join(''); // remove - this doesn't do anything
var letter_count = {}

for(var i of name){
   if (!(i in letter_count)){
    letter_count[i] = 1;
   }
  else {
   letter_count[i] += 1;
  }
}

console.log(letter_count);

Sign up to request clarification or add additional context in comments.

Comments

2

If you need a fancy functional programming approach:

const letterCount = name.toLowerCase().split('').reduce((acc, curr) => {
    acc[curr] ? acc[curr]++ : acc[curr] = 1;
    return acc;
}, {});

console.log(letterCount);

You can find the documentation of reduce function here: link

Comments

1

I think you were a little confused with how to use the i variable. It is actually the index of the character, not the character. To get the character, you need to use var c = name[i];

var name = "Interesting";
name = name.replace(/ +/g, "").toLowerCase();
name = name.split('').join('');
var letter_count = {}

for(var i in name){
   var c = name[i];
   if (!(c in letter_count)){
    letter_count[c] = 1;
   }
  else {
   letter_count[c] += 1;
  }
}

console.log(letter_count);

Comments

1

There are couple of unnecessary and mistaken things in your code and I put them in comments inside code

var name = "Interesting";
// you do not need to do this name = name.replace(/ +/g, "").toLowerCase();
name = name.toLowerCase();
// nor this name = name.split('').join('');
var letter_count = {}

for(var i in name){
   var character = name[i]; // here we set the value of character to be letter from name
   if (!(character in letter_count)){
    letter_count[character] = 1; // here we are giving it initial value if it is not found so far
   }
  else {
   letter_count[character] += 1; // here we are giving it value if it already exists
  }
}

console.log(letter_count);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.