数组中出现次数最高或在JavaScript中首次选中的事件
我们需要编写一个JavaScript函数,该函数接受一组文字值。然后,我们的函数应返回数组值的最高出现,并且如果存在相等的出现,则应返回相等出现的第一个选定值。
const arr = ['25', '50', 'a', 'a', 'b', 'c']
在这种情况下,我们应该返回“a”
const arr = ['75', '100', 'a', 'b', 'b', 'a']
在这种情况下,我也应该得到“a”
示例
为此的代码将是-
const arr = ['25', '50', 'a', 'a', 'b', 'c'];
const arr1 = ['75', '100', 'a', 'b', 'b', 'a'];
const getMostFrequentValue = (arr = []) => {
let count = 0, ind = -1;
arr.forEach((el, i) => {
this[el] = this[el] || { count: 0, ind: i };
this[el].count++;
if (this[el].count > count) {
count = this[el].count;
ind = this[el].ind;
return;
};
if (this[el].count === count && this[el].ind < ind) {
ind = this[el].ind;
};
}, Object.create(null));
return arr[ind];
};
console.log(getMostFrequentValue(arr));
console.log(getMostFrequentValue(arr1));输出结果
控制台中的输出将是-
a a
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便