# Sort elements by frequency of occurance

Hello, I am stuck on my school problem.
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.

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));`````````

Welcome there.

I am confused as to what output you actually want. Neither of the examples you gave had decreasing order?

Hello,
The output array should return array sorted by frequency of occurance. So from element with the biggest occurance to the smallest. But if the frequency (number of occurance) is the same it should print the element that came first in the original array first.
Hope that makes it more clear.

Right. My mind immediately went to Hertz when you said frequency, and I though the numbers represented frequency.

``````let index = {};

arr.forEach(function(value) {
let count = 0;
if ( value in b ){
b[value] = b[value] + 1;
}else{
b[value] = 1;
index[value] = count;
count++
}
});
``````

Use the index to know which came first. Use that logic in your sorting.

Hope this helps