数组中出现次数最多或 JavaScript 中首先选择的元素

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 14:04:17

我们需要编写一个 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

相关文章


有用资源