Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sorting an array order by frequency of occurence in javascript
/**
* Sorting an array order by frequency of occurence in javascript
* @param {array} array An array to sort
* @returns {array} array of item order by frequency
**/
function sortByFrequency(array) {
var frequency = {};
var sortAble = [];
var newArr = [];
array.forEach(function(value) {
if ( value in frequency )
frequency[value] = frequency[value] + 1;
else
frequency[value] = 1;
});
for(var key in frequency){
sortAble.push([key, frequency[key]])
}
sortAble.sort(function(a, b){
return b[1] - a[1]
})
sortAble.forEach(function(obj){
for(var i=0; i < obj[1]; i++){
newArr.push(obj[0]);
}
})
return newArr;
}
Example Suppose you have an array [2, 2, 1, 4, 2,5, 4,4,4, 5]
sortByFrequency([2, 2, 1, 4, 2,5, 4,4,4, 5])
Answer : [ '4', '4', '4', '4', '2', '2', '2', '5', '5', '1' ]
@vekannan

This comment has been minimized.

Copy link

vekannan commented Feb 13, 2020

Looks good but not sorted with index for sorting same count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.