找数组中出现最多的元素和次数

<script>
function findMost(arr) {
if (!arr.length) return;
if (arr.length === 1) return 1;
let res = {};
let maxName, maxNum = 0;
// 遍历数组
arr.forEach((item) => {
res[item] ? res[item] += 1 : res[item] = 1;;
});
// 遍历 res
for (let r in res) {
if (res[r] > maxNum) {
maxNum = res[r];
maxName = r;
}
}
return '出现次数最多的元素为:' + maxName + ', 出现次数为:' + maxNum;
}
console.log(findMost([1, 5, 5, 8, 6, 1, 8, 6, 7, 5]));
</script>
posted @ 2019-12-19 16:30  倔强的代码人  阅读(491)  评论(0编辑  收藏  举报