Last active
October 12, 2020 08:35
-
-
Save PostScripton/9f4836b82d1f12d429cc488d59bbf2b6 to your computer and use it in GitHub Desktop.
Allows to sort an array by frequency of occurence in JS
This file contains 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
const arr = [1, 2, 4, 5, 5, 5, 2, 4, 3, 4, 3, 3, 2, 3, 2, 1, 1, 2, 1] | |
Array.prototype.sortByFrequency = function () { | |
let frequency = {} | |
let sorting = [] | |
let new_arr = [] | |
this.forEach(value => frequency[value] = (frequency[value] || 0) + 1) | |
for (let key in frequency)sorting = [...sorting, [key, frequency[key]]] | |
sorting.sort((a, b) => b[1] - a[1]) | |
sorting.forEach(element => { | |
this.forEach(arr_element => { | |
if (arr_element.toString() === element[0]) | |
new_arr = [...new_arr, arr_element] | |
}) | |
}) | |
return new_arr | |
} | |
arr.sortByFrequency() | |
// OUTPUT: [ 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5 ] |
This file contains 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
const arr = [ | |
{ name: "John", score: 34 }, | |
{ name: "Lou", score: 12 }, | |
{ name: "George", score: 28 }, | |
{ name: "Mike", score: 34 }, | |
{ name: "Steve", score: 34 }, | |
{ name: "Sophie", score: 9 }, | |
{ name: "Emma", score: 12 }, | |
{ name: "John", score: 17 }] | |
Array.prototype.sortByFrequencyOf = function (attribute) { | |
if (!attribute) return [] | |
let frequency = {} | |
let sorting = [] | |
let new_arr = [] | |
this.forEach(value => frequency[value[attribute]] = (frequency[value[attribute]] || 0) + 1) | |
for (let key in frequency)sorting = [...sorting, [key, frequency[key]]] | |
sorting.sort((a, b) => b[1] - a[1]) | |
sorting.forEach(element => { | |
this.forEach(arr_element => { | |
if (arr_element[attribute].toString() === element[0]) | |
new_arr = [...new_arr, arr_element] | |
}) | |
}) | |
return new_arr | |
} | |
arr.sortByFrequencyOf('score') | |
/* OUTPUT: | |
[{ name: 'John', score: 34 }, | |
{ name: 'Mike', score: 34 }, | |
{ name: 'Steve', score: 34 }, | |
{ name: 'Lou', score: 12 }, | |
{ name: 'Emma', score: 12 }, | |
{ name: 'Sophie', score: 9 }, | |
{ name: 'John', score: 17 }, | |
{ name: 'George', score: 28 }] */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment