我正在寻找一种有效的解决方案来根据元素出现的次数对数组进行排序
例如:
let values = ["10", "4", "4", "4", "7", "7"]
我认为最好的输出类似于[{number,Frequency}, ...]
,在示例中如下所示:
[{4, 3}, {7, 2}, {10, 1}]
我已经看到了很多方法来做到这一点,但每个解决方案都只是根据频率对数组进行排序,而没有访问元素出现的次数。
目前我只有从另一个 StackOverflow 主题获得的代码(抱歉不记得是哪个)
var map = values.reduce(function(p, c) {
p[c] = (p[c] || 0) + 1;
return p;
}, {});
var newTypesArray = Object.keys(map).sort(function(a, b) {
return map[a] < map[b];
});
console.log(newTypesArray);
它在根据频率进行排序方面做得很好,但我无法访问元素重复的次数。而且我不知道该怎么做...... 有什么想法吗?
最佳答案
const arr = [1, 1, 1, 2, 2, 3];
// use reduce for that.
const result = arr.reduce((result, item) => {
const count = result[item];
if (count === undefined) {
result[item] = 1;
} else {
result[item] += 1;
}
return result;
}, {});
// You'll get the result similar to this: {[item]: [count]}
// And then you can transform it into entries array:
const entries = Object.entries(result);
// entries are [[item, count], ...];
// And then sort
const sorted = entries.sort((entryA, entryB) => entryA[1] - entryB[1]);
// You'll have ascending sorted array by count.
console.log(sorted);
关于javascript - 按元素出现频率对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57677147/