如何获取数组中最常见的值:JavaScript?
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

