在 JavaScript 中将元素出现次数限制为 n 次
问题
我们需要编写一个JavaScript函数,它接受一个整数数组arr,它可能包含重复项作为第一个参数,以及一个数字num作为第二个和最后一个参数。
我们函数的任务是遍历数组并检查数组中是否存在某个出现次数超过n次的数字。
如果存在任何这样的元素,我们应该删除它的额外出现以限制它的出现次数最多为num。
例如,如果函数的输入是-
输入
const arr = [4, 1, 3, 1, 4, 1, 3, 4, 2]; const num = 2;
输出
const output = [4, 1, 3, 1, 4, 3, 2];
输出说明
4和1都出现了三次,所以第三次出现被删除
示例
以下是代码-
const arr = [4, 1, 3, 1, 4, 1, 3, 4, 2];
const num = 2;
const deleteExtra = (arr = [], num = 1) => {
if(num === 0){
return [];
};
const res = [];
const map = {};
for(let i = 0; i < arr.length; i++){
const el = arr[i];
map[el] = (map[el] || 0) + 1;
if(map[el] <= num){
res.push(el);
};
};
return res;
};
console.log(deleteExtra(arr, num));输出结果[ 4, 1, 3, 1, 4, 3, 2 ]