I have:
myArray = [\"ABAB\", \"ABAB\", \"ABAB\", \"CDCD\", \"EFEF\", \"EFEF\"]
I need to count by occurrences and sort by highest count. This w
I recently created a library with such a function.
var items = {}, sortableItems = [], i, len, element,
listOfStrings = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"];
for (i = 0, len = listOfStrings.length; i < len; i += 1) {
if (items.hasOwnProperty(listOfStrings[i])) {
items[listOfStrings[i]] += 1;
} else {
items[listOfStrings[i]] = 1;
}
}
for (element in items) {
if (items.hasOwnProperty(element)) {
sortableItems.push([element, items[element]]);
}
}
sortableItems.sort(function (first, second) {
return second[1] - first[1];
});
console.log(sortableItems);
Output
[ [ 'ABAB', 3 ], [ 'EFEF', 2 ], [ 'CDCD', 1 ] ]