我有一个数组,它是根据从 api 调用中提取的值填充的。 该数组将具有这样的值
["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"]
我想要做的是获取数组中每个项目出现的次数,并根据计数对它进行降序排序。
我做了这个,这是我从 stackoverflow 得到的:
data.forEach(function (x) {
counts[x] = (counts[x] || 0) + 1;
});
最佳答案
另一种方法是使用函数reduce
来计数并使用计数创建一个对象,然后使用函数sort
。
如果你想通过“名称”提取特定对象,可以使用函数find
:
let array = ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"],
counts = Object.values(array.reduce((a, c) => {
(a[c] || (a[c] = {name: c, count: 0})).count += 1;
return a;
}, {})).sort(({count: ac}, {count: bc}) => bc - ac),
target = "2.4",
found = counts.find(({name}) => name === target);
console.log(counts);
console.log(found);
console.log(found.count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - typescript 计算数组中的重复项并按每个项目的计数对结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662639/