Created
December 1, 2016 10:26
-
-
Save niteshpsit1/c90b3336ee639c89ae13b98825c9d9ca to your computer and use it in GitHub Desktop.
Sorting an array order by frequency of occurence in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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]));
}