Hello, I am stuck on my school problem.
The task is:
Print the elements of an array in the decreasing frequency (number of occurances),if 2 numbers have same frequency then print the one which came first.
How would you do that in Javascript?
I am having difficulties with the part when two elements have same frequency to print the one that came first.
Thank you for your help.
Examples:
Input: arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6}
Input: arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}
Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999}
My code, but it does not print the one that came first.
function sortbyFrequency(arr) {
var sortAble = [];
var results = [];
var b = {};
arr.forEach(function(value) {
if ( value in b ){
b[value] = b[value] + 1;
}else{
b[value] = 1;
}
});
for(var key in b){
sortAble.push([key, b[key]])
}
sortAble.sort(function(a, b){
return b[1] - a[1]
})
sortAble.forEach(function(obj){
for(var i=0; i < obj[1]; i++){
results.push(obj[0]);
}
});
return results;
}
let arr = [5,2,2,8,5,6,8,8];
console.log(sortbyFrequency(arr));```