Last active
February 17, 2016 14:26
-
-
Save tuscen/ce563b395e6074d14620 to your computer and use it in GitHub Desktop.
Sort elements in array by their frequencies
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
| function sortByFrequencies(coll) { | |
| 'use strict'; | |
| const frequencies = coll.reduce((freq, elem) => { | |
| if (freq.has(elem)) { | |
| return freq.set(elem, freq.get(elem) + 1); | |
| } else { | |
| return freq.set(elem, 1); | |
| } | |
| }, new Map()); | |
| const sortedFreq = []; | |
| for (let item of frequencies.entries()) { | |
| sortedFreq.push(item); | |
| } | |
| sortedFreq.sort((prev, curr) => { | |
| const compared = curr[1] - prev[1]; | |
| if (!compared) { | |
| return coll.indexOf(prev[0]) - coll.indexOf(curr[0]); | |
| } else { | |
| return compared; | |
| } | |
| }); | |
| return sortedFreq.reduce((sorted, [item, frequency]) => { | |
| const repeatedItem = new Array(frequency).fill(item); | |
| return sorted.concat(repeatedItem); | |
| }, []); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment