1

I want to know that how many times each alphabet comes in the 'input' variable. For this I am loop through each character and storing them in an object and also how many they appeared in the sentence. But It is consoling NaN. Please show me where is the error?

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;
    });
    console.log(object);
} 
1
  • For starters, object[item] == 'undefined' needs to be object[item] == undefined with no quotes around undefined and it would be even better to use object[item] === undefined with the === so there's no type conversion going on. Though, I personally would use object.hasOwnProperty(item) myself. Commented Oct 3, 2015 at 16:57

3 Answers 3

1

You can use hasOwnProperty to check if a property exists.

var input = "why this kolaveri kolaveri di";


var object = {};
input.replace(/\s/g,"").split("").forEach(function(item){
  
  // If the property doesn't exist, initialize it to 0
  if (!object.hasOwnProperty(item))
    object[item] = 0;
  
  object[item]++
});
console.log(object);
 

For the haters, you can initialize to 1 and only increment in the else. Essentially the same but a few cycles more efficient. Use whichever you think looks best.

  // If the property doesn't exist, initialize it to 1
  if (!object.hasOwnProperty(item))
    object[item] = 1;
  else
    object[item]++;
Sign up to request clarification or add additional context in comments.

Comments

0

This work

  typeof object[item] == 'undefined' ?

Comments

0

You had the problem in the below line of code .

object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;

Update Code:

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        if(object[item] == null)
        { 
            object[item] = 0;
            object[item]++; 
        }else{
            object[item]++;
        }
    });
    console.log(object);
}

//testing here 
processData(input);

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.