如何獲取陣列中最常見的元素值:JavaScript ?


我們需要編寫一個 JavaScript 函式,該函式接受一個包含重複值的字面量陣列。我們的函式應返回陣列中最常見元素的陣列(如果兩個或多個元素的出現次數相同,則陣列應包含所有這些元素)。

示例

程式碼如下 −

const arr1 = ["a", "c", "a", "b", "d", "e", "f"];
const arr2 = ["a", "c", "a", "c", "d", "e", "f"];
const getMostCommon = arr => {
   const count = {};
   let res = [];
   arr.forEach(el => {
      count[el] = (count[el] || 0) + 1;
   });
   res = Object.keys(count).reduce((acc, val, ind) => {
      if (!ind || count[val] > count[acc[0]]) {
         return [val];
      };
      if (count[val] === count[acc[0]]) {
         acc.push(val);
      };
      return acc;
   }, []);
   return res;
}
console.log(getMostCommon(arr1));
console.log(getMostCommon(arr2));

輸出

控制檯中的輸出將是 −

[ 'a' ]
[ 'a', 'c' ]

更新於: 21-11-2020

387 瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.