JavaScript数组:查找出现次数超过n次的所有元素
我们有一个数字/字符串文字数组,其中包含一些重复的条目。我们的工作是编写一个接受正整数Numbern并返回所有元素的子数组的函数,该子数组使外观大于或等于only参数指定的numbern。
因此,让我们为该函数编写代码-
我们将使用aMap()来保留元素频率的计数,然后返回超出指定计数的元素。为此的代码将是-
示例
const arr = [34, 6, 34, 8, 54, 7, 87, 23, 34, 6, 21, 6, 23, 4, 23];
const moreThan = (arr, num) => {
const creds = arr.reduce((acc, val) => {
let { map, res } = acc;
const count = map.get(val);
if(!count && typeof count !== 'number'){
map.set(val, 1);
}else if(num - count <= 1){
res.push(val);
} else {
map.set(val, count+1);
};
return {map, res};
}, {
map: new Map(),
res: []
});
return creds.res;
};
console.log(moreThan(arr, 3));输出结果
控制台中的输出将为-
[34, 6, 23]