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 ]

更新于: 2021年4月22日

179 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.