Count unique entries, create an array of uniques, then sort based upon counts
function count(arr) { // count occurances
var o = {}, i;
for (i = 0; i < arr.length; ++i) {
if (o[arr[i]]) ++o[arr[i]];
else o[arr[i]] = 1;
}
return o;
}
function weight(arr_in) { // unique sorted by num occurances
var o = count(arr_in),
arr = [], i;
for (i in o) arr.push(+i); // fast unique only
arr.sort(function (a, b) {
return o[a] < o[b];
});
return arr;
}
weight([1, 3, 3, 5, 5, 5, 2, 2, 2, 2]);
// one 1, two 3s, three 5s, four 2s
// [2, 5, 3, 1]
You example has both one 9
and one 4
, so if you want the order defined, more work would be necessary. Otherwise;
weight([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
// [2, 3, 5, 4, 9]
To produce an Array of Objects
function weight(arr_in) { // unique sorted by num occurances
var o = count(arr_in),
arr = [], i;
for (i in o) arr.push({value: +i, weight: o[i]}); // fast unique only
arr.sort(function (a, b) {
return a.weight < b.weight;
});
return arr;
}
var result = weight([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
/* [
{"value": 2, "weight": 5},
{"value": 3, "weight": 4},
{"value": 5, "weight": 3},
{"value": 4, "weight": 1},
{"value": 9, "weight": 1}
] */
Now, to get the value at index i
, you do result[i].value
, and for it's weighting result[i].weight
.