在 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