-9

So basically I need a script that summarizes which characters and the number of times they appear in a random string. Caps have to be ignored, for example:

var myString = promt ("Type anything: "); //"hello Hello";

The end result has to be something like this: h = 2, e = 2, l = 4, o = 2 printed in the HTML document.

I've tried using myString.match().length without much success. My main problem is defining which characters to check and not checking characters twice (for example: if there are two "h" in the string not checking them twice).

  • 3
    Show us please what have you tried so far so we can help. – Zakaria Acharki Apr 12 '16 at 15:14
  • 1
    Also, your question is unclear. _"`not checking characters twice (for example: if there are two "h" in the string not checking them twice)`"_ But then in your example you have two "h" characters and you do count both of them. – j08691 Apr 12 '16 at 15:15
  • 2
    This looks like a fun homework question. Seeing as you've not posted more than a fragment of your code, have you tried using an array? – Hugo Yates Apr 12 '16 at 15:16

2 Answers2

0
var str = 'hello Hello';
var count = {};
str.split('').forEach(function(v) {
    if (v === ' ') return;
    v = v.toLowerCase();
    count[v] = count[v] ? count[v] + 1 : 1;
})

console.log(count);
navid
  • 566
  • 6
  • 15
baao
  • 71,625
  • 17
  • 143
  • 203
0

You can use temporary object

var o = {};

"hello Hello".toLowerCase()
    .replace(/\s+/, '')
    .split('')
    .forEach(e => o[e] = ++o[e] || 1);

document.write(JSON.stringify(o));

This solution uses arrow function (ES2015 standard) that doesn't work in old browsers.

isvforall
  • 8,768
  • 6
  • 35
  • 50
  • 1
    You should note that this only works in ES6. *See* [What's the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript?](http://stackoverflow.com/a/24900924/2057919). It doesn't work in the versions of JavaScript available in many browsers. (And, of course, it's bad policy to do people's homework for them when they haven't made any real effort.) – elixenide Apr 12 '16 at 15:33