Reputation: 431
OKAY, so I have a bunch of numbers in a div, lets say something like...
<div id="countme">7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8</div>
And I want to use JavaScript to return...
Example Output: "(2,0),(1,2),(3,3),(2,5),(1,6),(1,7),(1,8)"
Explained: Zero appears two times, two appears one time, three appears three times, etc...
I've tried the following...
var str = document.getElementById('countme').innerText;
var match = str.match(/7/g);
var match1 = str.match(/5/g);
alert(match.length);
alert(match1.length);
But I need it to display the number it searched for, and I need everything to be in one alert.
Any thoughts?
Thanks! :)
Upvotes: 2
Views: 370
Reputation: 463
I think this is almost as efficient as you can get. It also serves as a general count unique matches method:
var testString = document.getElementById('countme').innerText;
count = {};
var regX = /(\d+)/g;
var res;
while (res = regX.exec(testString )) {
count[res[0]] = (count[res[0]] !== undefined ? ++count[res[0]] : 1)
};
Upvotes: 0
Reputation: 26163
Try this...
var str = "7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8";
str = str.replace(/\s/g, "");
str = str.split(",");
var result = {};
str.forEach(function(value) {
if (result[value]) {
result[value]++;
}
else {
result[value] = 1;
}
});
var output = "";
for(value in result) {
output += (output == "" ? "" : ",") + "(" + value + "," + result[value] +")";
}
alert(output);
It splits the string and removes any whitespace, so you're left with an array (and no assumption that the delimiter is consistent).
It then creates an object representing each value and the count.
It finally converts that into an output, similar to the one in your example.
Upvotes: 0
Reputation: 46
Here is the Answer
var str = document.getElementById('countme').innerText;
var array = JSON.parse("[" + str+ "]");
var counts = {};
array.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts);
Upvotes: 0
Reputation: 13896
JSBIN: https://jsbin.com/tesezoz/1/edit?js,console
var str = "7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8";
// first get the numbers
var m = str.split(', ').map(Number);
// turn it into an object with counts for each number:
var c = m.reduce(function(a, b) {
a[b] = ++a[b] || 1;
return a;
}, {});
// now you have an object that you can check for the count
// which you can alert... its the c variable
Upvotes: 1