我有这种数组:
let mixedArr = ["Ship", "Ship", "Boat", "Ship", "Boat", "yacht" ]
我需要一个按外观对数组进行排序的结果,如下所示:
let sortedMixedArr = ["Ship", "Boat", "Yacht"]
谁可以提出解决方案?
答案 0 :(得分:0)
您需要对项目进行计数,然后按计数对条目进行排序
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
}
答案 1 :(得分:0)
使用地图的键并按计数对它们进行排序的一种较短方法。
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);