The long way
var elements = ["apple", "apple", "orange", "apple", "banana"];
elements.sort();
var current = null;
var count = 0;
for(var i = 0; i < elements.length; i++)
{
if(elements[i] != current)
{
if(count > 0)
{
document.write(current + " " + count + "<br/>");
}
current = elements[i];
count = 1;
}
else
{
count++;
}
}
if(count > 0)
{
document.write(current + " " + count);
The short way
var elements = ["apple", "apple", "orange", "apple", "banana"];
var counts = {};
elements.forEach(function(x) {
counts[x] = (counts[x] || 0) + 1;
});
document.write("Apple: " + counts.apple + "<br/>");
document.write("Banana: " + counts.banana + "<br/>");
document.write("Orange: " + counts.orange + "<br/>");