Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
sort_array_by_element_frequency solution in Clear category for Sort Array by Element Frequency by Jon_Red
import assert from'assert';
function frequencySort(items:any[]):any[]{
var freq={};
items.forEach(x=>x in freq?freq[x]++:freq[x]=(1/(items.indexOf(x)+1)));
return items.sort((a,b)=>freq[b]-freq[a]);
}
// self-checks
assert.deepEqual(frequencySort([4,6,2,2,6,4,4,4]),[4,4,4,4,6,6,2,2]);
assert.deepEqual(
frequencySort(['bob','bob','carl','alex','bob']
),['bob','bob','bob','carl','alex']);
assert.deepEqual(frequencySort([17,99,42]),[17,99,42]);
assert.deepEqual(frequencySort([]),[]);
assert.deepEqual(frequencySort([1]),[1]);
July 24, 2020