我有一个字符串数组:
array = ["Henry","Brian","Henry","Matilda","Henry","Brian","Matthew"]
并希望将它们排序到一个列表中,该列表首先按最常出现的项目对数组进行排序,但之后又将其删除以创建一个列表,如下所示:
sortedArray = ["Henry","Brian","Matilda","Matthew"]
有没有办法做到这一点的JavaScript?
最佳答案
您可以使用在O(nlogn)而不是O(n²)中运行的ES6函数作为其他解决方案:
var array = ["Henry","Brian","Henry","Matilda","Henry","Brian","Matthew"]
var result = [...array.reduce( (acc, s) => acc.set(s, (acc.get(s) || 0)+1), new Map )]
.sort( (a, b) => b[1] - a[1] )
.map( a => a[0] );
console.log(result);
它首先通过保留每个字符串的计数(以线性时间运行)来创建映射。
然后,将此映射转换为成对的数组(扩展为
[... ]
),然后根据该计数对其进行排序(O(nlogn))。最后,使用
.map()
从该数组再次删除计数关于javascript - 用最常见的项目在javascript中排序数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41333763/