Skip to content

Instantly share code, notes, and snippets.

@niteshpsit1
Created December 1, 2016 10:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save niteshpsit1/c90b3336ee639c89ae13b98825c9d9ca to your computer and use it in GitHub Desktop.
Save niteshpsit1/c90b3336ee639c89ae13b98825c9d9ca 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' ]
@tazimmadre-saharsh
Copy link

tazimmadre-saharsh commented Jun 21, 2022

function SortElemByFrequencyObj(arr) {
const frequency = arr.reduce((obj, curr) => {
obj[curr] = (obj[curr] || 0) + 1;
return obj;
}, {});
return Object.entries(frequency).sort((a, b) => b[1] - a[1]).flatMap(item => Array(item[1]).fill(item[0]))
}

you can make this code compact by using lodash _.count method

import _ from 'lodash';
function SortElemByFrequencyObj(arr) {
const frequency = _.count(arr);
return Object.entries(frequency).sort((a, b) => b[1] - a[1]).flatMap(item => Array(item[1]).fill(item[0]));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment