0

I've been trying to figure out how to count how many times a character happens in a string and store it in another variable that will hold the character and the number of times it occurs in the string.

For example:

var greeting = "Hello World";

[H] occurs [1] time.

[e] occurs [1] time.

[l] occurs [3] times.

[o] occurs [2] times.

[W] occurs [1] time.

[r] occurs [1] time.

[d] occurs [1] time.

I am a JS Beginner and I tried as much as I can following guides and tutorials but this exercise seems to be out of my league. I would appreciate some help as to how would you guys go on about solving this problem.

Thanks!

Cardanos
  • 3
  • 2
  • Possible duplicate, see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string – DominicEU Jan 29 '16 at 21:49

2 Answers2

0

You basically want to create a mapped set of characters to it's count in the string. Storing this stuff in an array might be weird as you'd need 2 Dimentional arrays. Instead store it in an hash object.

var greeting = "Hello world!";

var hash = {};
for(var i = 0; i < greeting.length; i++){
  if(hash[greeting[i]] === undefined){
    hash[greeting[i]] = 1;
  } else {
    hash[greeting[i]] += 1;
  }
}

// printing the stuff in hash.
for(var x in hash){
  if(hash.hasOwnProperty(x)){
    console.log(x, hash[x]);
  }
}

Anyway if you need this stuff in array, you can put so:

var arr = [];
var i = 0;
for(var x in hash){
  if(hash.hasOwnProperty(x)){
    arr[i++] = [x, hash[x]];
  }
}

for(var i = 0; i< arr.length; i++){
  console.log(arr[i]);
}

But I wouldn't recommend it. You can see redundancy for yourself.

0

Try this:

var result = {};

Array.prototype.map.call('Hello world!', function(x) {
  if (typeof result[x] == 'undefined') {
    result[x] = 1;
  } else {
    result[x] += 1;    
  }
});
console.log(result);

var result = {};

Array.prototype.map.call('Hello world!', function(x) {
  if (typeof result[x] == 'undefined') {
    result[x] = 1;
  } else {
    result[x] += 1;    
  }
});
console.log(result);
cFreed
  • 4,404
  • 1
  • 23
  • 33