Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudharsan203/07d17ec05aeeee8544a19610486f2c6f to your computer and use it in GitHub Desktop.
Save sudharsan203/07d17ec05aeeee8544a19610486f2c6f to your computer and use it in GitHub Desktop.
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' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment