Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Sort Array by Element Frequency by ArchTauruS
import assert from "assert"
function frequencySort(items: any[]): any[] {
// your code here
return items.sort((a, b) => {
const counta = items.filter(e => e == a).length
const countb = items.filter(e => e == b).length
return countb - counta || items.indexOf(a) - items.indexOf(b)
})
}
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!")
Sept. 15, 2020