Count how many strings in a table have duplicates in the same array

advertisements

Possible Duplicate:
Array value count javascript

I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.

The array looks something like this

array = ['aa','bb','cc','aa','ss','aa','bb'];

Thus I would like to do something like this

if (xWordOccurrences >= 5) {
    // do something
}

But I'm not sure how I would code this. I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...

But this seems like an over complexe way to do it.


You can use an object which has keys of the Array's values and do something like this

// count everything
function getCounts(arr) {
    var i = arr.length, // var to loop over
        obj = {}; // obj to store results
    while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
    return obj;
}

// get specific from everything
function getCount(word, arr) {
    return getCounts(arr)[word] || 0;
}

getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3

If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2

function getCount2(word, arr) {
    var i = arr.length, // var to loop over
        j = 0; // number of hits
    while (i) if (arr[--i] === word) ++j; // count occurance
    return j;
}

getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3