数组中出现次数最高或在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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短