Sasha
Sasha

Reputation: 23

Increment Javascript object member dynamically

Essentially, I desire the function to read all letters from a string, and to spit out an object that contains {'letter', 'count'} properties for each letter.

function freqLetters(string) {
  var freq = [];
  for (var i = 0; i < string.length; i++) {
    var character = string.charAt(i);
    if (typeof freq[character] != undefined) {
      freq[character].count++;
    } else {
      freq.push({'letter': character, 'count': 1});
    }
  }

  return freq;
}

However, freq usually appears empty and when it works, it seems to always fail the '!=== undefined' check and push duplicate letters of 1 count, rather than finding them and increment them.

Is the typeof freq[character] !=== undefined] check correct?

How on earth do I increment dynamic elements?

(i.e. find letter:a if it exists, and increment its count by 1 if it exists)

Upvotes: 0

Views: 349

Answers (3)

Karthikeyan
Karthikeyan

Reputation: 21

You could use the below code:

function countCharacters(exampleString){
var countObject = {} ; 
for (var i = 0, l = exampleString.length; i < l; i++) {
    var currentChar =  exampleString.charAt(i);
    if(typeof(currentChar) != undefined) {
        countObject[currentChar] = characterCount(exampleString, currentChar);
    }
}
console.log(countObject);
return(countObject); }



function characterCount(word, character) {
   var count = 0;
    for (var i = 0; i < word.length; i++) {
       if (word[i] === character) {
           count++;
       }
  }
  return count; }

Hope it helps :)

Upvotes: 0

Piercey4
Piercey4

Reputation: 1358

Functional programming woo.

var counts = string
    .split('') // Get individual letters.
    .reduce((acc, letter)=> {
        // acc is an object (passed in as second arg to reduce).
        // we use the existing value for the letter (default to 0) and add one each time.
        acc[letter] = (acc[letter] || 0) + 1
        return acc
    }, {})

Edit: Realized you wanted an array or { letter: count } objects.

var countsList = Object
    .keys(counts)
    .map((key)=> ({ [key]: counts[key] }))

Upvotes: 2

Silvinus
Silvinus

Reputation: 1445

If you want to check existence of letter, don't use an array object. Because push function add element indexed by number (0, 1, 2) so freq[character] is always undefined.

For your instanciation :

var freq = {};

in your else :

freq[character] = {'letter': character, 'count': 1}

And in your if, check just the existence :

if (freq[character]) {... }

Upvotes: 0

Related Questions