Identify distinct entries, form an array of distinct values, then arrange them based on frequency
function count(arr) { // calculate occurrences
var obj = {}, index;
for (index = 0; index < arr.length; ++index) {
if (obj[arr[index]]) ++obj[arr[index]];
else obj[arr[index]] = 1;
}
return obj;
}
function sortArray(arr_input) { // distinct values sorted by frequency
var obj = count(arr_input),
finalArr = [], index;
for (index in obj) finalArr.push(+index); // quickly obtain distinct only
finalArr.sort(function (a, b) {
return obj[a] < obj[b];
});
return finalArr;
}
sortArray([1, 3, 3, 5, 5, 5, 2, 2, 2, 2]);
// one 1, two 3s, three 5s, four 2s
// [2, 5, 3, 1]
Your example includes both a 9
and a 4
, so if you require a specific order, further adjustments would be needed. Otherwise;
sortArray([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
// [2, 3, 5, 4, 9]
To generate an Array of Objects
function sortArray(arr_input) { // distinct values sorted by frequency
var obj = count(arr_input),
finalArr = [], index;
for (index in obj) finalArr.push({value: +index, weight: obj[index]}); // quickly get distinct values only
finalArr.sort(function (a, b) {
return a.weight < b.weight;
});
return finalArr;
}
var result = sortArray([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 access the value at position i
, use result[i].value
, and for its weightage result[i].weight
.