在 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

更新日期: 24-Nov-2020

105 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.