Q:

JavaScript sort Array by uniqueness

I have an array of items. For example:
var classes = ['link', 'block', 'hide', 'link', 'menu', 'block', 'content', 'link', 'footer', 'img', 'img', 'link', 'modal', 'button', 'form', 'input', 'button', 'input', 'link', 'toString', 'valueOf', 'button'];

I need to get an array of unique items, sorted by frequency:
'link' item should be in the first place, because array contain it 5 times.
'button' item should be in the second place, because array contain it 3 times.
etc
["link", "button", "input", "img", "block", "footer", "content", "modal", "menu", "form", "hide", "toString", "valueOf"]

A:

You can obtain it easily using ECMAScript 5 methods:
var classes = ['link', 'block', 'hide', 'link', 'menu', 'block', 'content', 'link', 'footer', 'img', 'img', 'link', 'modal', 'button', 'form', 'input', 'button', 'input', 'link', 'toString', 'valueOf', 'button'];

var frequency = classes.reduce(function(data, item) {
    data[item] = -~data[item];
    return data;
}, {});

var uniques = Object.keys(frequency).sort(function(a, b) {
    return frequency[b] - frequency[a];
});

console.log(uniques);

If you have to support old browsers, you can still use the shims.

