我写了一个JS代码来查找数组中每个元素的频率。这是我的代码,并且可以正常工作。我的问题是,在简单性方面是否有更好的解决方案?
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 4, 5, 8, 8, 1, 2, 8, 5, 4, 8, 4];
const counts = [];
const minOfArr = Math.min(...arr);
const maxOfArr = Math.max(...arr);
for (let i = minOfArr; i <= maxOfArr; i++) {
const value = i.toString();
counts.push({
value: value,
frequency: 0
})
}
arr.forEach(elem => {
counts.forEach(entry => {
if (entry.value === elem.toString()) {
entry.frequency += 1;
}
})
})
console.log(counts);