在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP