0

I have a string like this: (apple,apple,orange,banana,strawberry,strawberry,strawberry). I want to count the number of occurrences for each of the characters, e.g. banana (1) apple(2) and strawberry(3). how can I do this?

The closest i could find was something like, which i dont know how to adapt for my needs:

function countOcurrences(str,   value){
 var regExp = new RegExp(value,     "gi");
return str.match(regExp) ?  str.match(regExp).length : 0;  
}
Ilija Dimov
  • 5,221
  • 7
  • 35
  • 42
tarlemn
  • 29
  • 4

3 Answers3

0

Here is the easiest way to achieve that by using arrays.. without any expressions or stuff. Code is fairly simple and self explanatory along with comments:

var str = "apple,apple,orange,banana,strawberry,strawberry,strawberry";

var arr = str.split(',');  //getting the array of all fruits

var counts = {};  //this array will contain count of each element at it's specific position, counts['apples']
arr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; }); //checking and addition logic.. e.g. counts['apples']+1

alert("Apples: " + counts['apple']);
alert("Oranges: " + counts['orange']);
alert("Banana: " + counts['banana']);
alert("Strawberry: " + counts['strawberry']);

See the DEMO here

Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43
  • Thank you all for your help its doing what I need now, quick follow up question if i want to change and point it to look at the contents in the file and count occurrences rather than specify within the var str= how would that work? – tarlemn Sep 15 '14 at 12:01
  • you can vote up the answer if it helped.. and you'll first have to read the file content in a string and then follow the procedure.. you can't just do it without reading the file first. – Abdul Jabbar Sep 15 '14 at 12:02
  • i keep voting up the answer but it wont save for some reason, dont know if its saved it now...okay i will look into that thanks – tarlemn Sep 15 '14 at 12:06
0

You can try

var wordCounts = str.split(",").reduce(function(result, word){
 result[word] = (result[word] || 0) + 1;
 return result;
}, {});

wordCounts will be a hash {"apple":2, "orange":1, ...}

You can print it as the format you like.

See the DEMO http://repl.it/YCO/10

Stoneboy
  • 201
  • 1
  • 8
0

You can use split also:

function getCount(str,d) {
    return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3
SK.
  • 4,174
  • 4
  • 30
  • 48