如何獲取陣列中最常見的元素值: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' ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP