1

I want to populate an object with the run length encoding of a string. Using an array this would generally be pretty simple, but I'm not quite sure what to do for an object.

function addto (string) {  
   var string = string.split("").sort();
   var cnt = 1;
   var obj = {};

   for (i = 0; i < string.length; i ++) {
     if (string[i] === string[i+1])
       cnt++;

   }

   return obj;
}

addto("abbccc");

Now obviously I can't use a method like push() here. But I also can't set the object name to the string at position i like so:

obj.string[i] = cnt;

Which is what I initially hoped to do. Is there a proper way to do this so that my output would be (for the example given):

{"a":1, "b":2, "c":3}

1 Answer 1

3

For every character in the string, you want to increment the obj counter for that character once. Here is a push in the right direction.

var obj = {};
for (i = 0; i < string.length; i ++) {
  // If the character has not been seen yet, set its counter to 0.
  obj[string[i]] = obj[string[i]] || 0;
  // Increment that character's count once.
  obj[string[i]]++;
}

Note that with this direction, you do not need to sort the array beforehand.

Here's another alternative. If you're doing this as coursework, then don't use this. But as a mental exercise I leave the solution:

var str = "abbccccddeeeeefgh"
var matches = str.match(/(.)\1*/g);
// matches = ["a", "bb", "cccc", "dd", "eeeee", "f", "g", "h"]
var counts = {};
for (i in matches)
  counts[matches[i][0]] = matches[i].length;
// counts = Object {a: 1, b: 2, c: 4, d: 2, e: 5, f: 1, g: 1, h: 1}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Joe, this was just what I was looking for, I'll accept as soon as I can!

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.