user4981236
user4981236

Reputation:

Creating a frequency listing of characters

charFreq function that's not quite working out. Hit a wall. I know I may need to do a conditional. Calling the function returns an Object error. I'm attempting to get string into an empty object displaying the characters like this - Object
{o: 4, p: 5, z: 2, w: 4, y: 1…}. New to Javascript by the way.

Just realized I shouldn't be appending anything. Do I need to do a .push() to
push the array into the object?

function charFreq (string){ 
 var emptyObj = {};

   for(var i = 0; i < string.length; i++) {
     // console.log(string.charAt(i));
     var args = [string.charAt(i)];
     var emptyArr = [''].concat(args);
     emptyObj += emptyArr
   }

  return emptyObj 
}

undefined

charFreq('alkdjflkajdsf')

"[object Object],a,l,k,d,j,f,l,k,a,j,d,s,f"

Upvotes: 0

Views: 362

Answers (3)

Schien
Schien

Reputation: 3903

A modified version of Richard Kho's code:

   function charFreq(string) {
      var obj = {};

      for (var i = 0; i < string.length; i++) {
        var c=string[i];
        if (c=='') continue;
        if (obj[c]==null) obj[c]=0;
        obj[c]++;
      }

      return obj;
    }

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19485

Try this instead: you need to create an object property first, then increment it. What you do, is implicitly convert the object to a string and concatenate more string data to it (using += and concat).

This is a simple approach:

function charFreq(string){ 
  var emptyObj={};
    for(var i=0; i<string.length; i++) {
      if(!emptyObj.hasOwnProperty(string[i])){ // if property doesn’t exist
        emptyObj[string[i]]=0;                 // create it and set to 0
      }
      emptyObj[string[i]]++;                   // increment it
    }
  return emptyObj;
}

Upvotes: 0

Richard Kho
Richard Kho

Reputation: 5286

You just need to set emptyObj's key of that specific letter to either 1 if it doesn't exist or increment the count if it already does.

function charFreq(string) {
  var obj = {};

  for (var i = 0; i < string.length; i++) {
    if (!obj.hasOwnProperty(string[i])) {
      obj[string[i]] = 1;
    } else {
      obj[string[i]]++;
    }
  }

  return obj;
}
console.log(charFreq('alkdjflkajdsf'));

Upvotes: 3

Related Questions