[英]Get the items that occur the most number of times in an javascript array
假设我有一个数组 a = [25, 2,3,57,38,41]
我想找到的是出现次数最多的数字,例如,
对于数组a ,输出将是 [2, 3, 5],因为 2、3 和 5 在数组中各出现 2 次。
你可以尝试这样的事情:
let freqs = [25, 2,3,57,38,41].map(n => n.toString().split("")).flat().reduce((acc, digit) => {
if (!acc[digit]) {
acc[digit] = 0
}
acc[digit] ++;
if (acc[digit] > acc.max) {
acc.max = acc[digit]
}
return acc;
}, {max: 0})
let max = freqs.max
delete freqs.max
Object.entries(freqs).filter(entry => entry[1] === max).map(entry => entry[0])
这是做什么的:
n.toString().split("")
将数字拆分为数字flat
创建一个包含所有数字的数组reduce
计算字符频率您可以计算并构建最大计数项目的数组。
const array = [25, 2, 3, 57, 38, 41], result = Array .from(array.join('')).reduce((r, d) => { r[d] = (r[d] || 0) + 1; (r[-r[d]] ??= []).push(+d); if (r.max < r[d]) { r.max = r[d]; r.result = r[-r[d]]; } return r; }, { max: 0 }) .result; console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.