数组中出现次数最高或在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 道士结婚文案祝福语简短