在 JavaScript 中将元素出现次数限制为 n 次

javascriptweb developmentfront end technology

问题

我们需要编写一个 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 ]

相关文章