Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Sort Array by Element Frequency (Map + sort iterator) solution in Clear category for Sort Array by Element Frequency by Alex_Yanul
import assert from "assert";
function frequencySort(items: any[]): any[] {
let map = new Map();
// add sort
map[Symbol.iterator] = function* () {
yield* [...this.entries()].sort((v1, v2) => v2[1] - v1[1]);
}
// Map [value, count]
items.forEach(i => {
let v = 1 + (map.get(i) ?? 0);
map.set(i, v);
});
// Note
// ! [...map] - sorted order!!!
// ! [map].entries - not sorted order
return [...map].map(v => Array(v[1]).fill(v[0])).flat();
}
console.log('Example:');
console.log(frequencySort([4, 6, 2, 2, 6, 4, 4, 4]));
// These "asserts" are used for self-checking and not for an auto-testing
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]);
console.log("Coding complete? Click 'Check' to earn cool rewards!");
Jan. 21, 2021
Comments: