I have this kind of array:
let mixedArr = ["Ship", "Ship", "Boat", "Ship", "Boat", "yacht" ]
I need a result that sorts the array by appearance, like this:
let sortedMixedArr = ["Ship", "Boat", "Yacht"]
Who can come up with a solution?
I have this kind of array:
let mixedArr = ["Ship", "Ship", "Boat", "Ship", "Boat", "yacht" ]
I need a result that sorts the array by appearance, like this:
let sortedMixedArr = ["Ship", "Boat", "Yacht"]
Who can come up with a solution?
You need to count items and then sort entries by count
let mixedArr = ["Ship", "Ship", "Boat", "Ship", "Boat", "yacht" ]
console.log(
sortByCount(mixedArr)
)
function sortByCount(arr) {
return [...arr.reduce((map, item) => {
if(map.has(item)) {
map.set(item, map.get(item) + 1)
} else {
map.set(item, 1)
}
return map
}, new Map).entries()] // create [[name, count]]
.sort(([_, a], [__, b]) => b - a) // sort by count numerically
.map(([name]) => name) // extract names
}
A shorter approach by using the keys of the map and sort them by the count.
var array = ["Ship", "Ship", "Boat", "Ship", "Boat", "Yacht"],
map = array.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map),
result = [...map.keys()].sort((a, b) => map.get(b) - map.get(a));
console.log(result);