在 JavaScript 中从数组中删除任何数字/元素的奇数出现

来自:互联网
时间:2023-09-06
阅读:

在 <a href=https://www.freexyz.cn/dev/JavaScript/ target=_blank class=infotextkey>JavaScript</a> 中从数组中删除任何数字/元素的奇数出现

假设我们有一个像这样的数字数组 -

const arr = [1, 6, 3, 1, 3, 1, 6, 3];

我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组作为第一个也是唯一的参数。然后该函数应该在数组中查找出现奇数次(不包括仅一次)的所有此类数字。

例如,

在上面的数组中,数字1 和 3 都出现了 3 次(奇数),因此我们的函数应该删除这两个数字的第三次出现。

输出数组应该如下所示 -

const output = [1, 6, 3, 1, 3, 6];

我们将准备一个哈希映射来跟踪每个数字的出现次数,最后我们将迭代该映射以删除最后一次出现的出现奇数次的该数字。

映射中的每个键都将保存一个数组值,其中第一个元素是该元素出现的次数,第二个元素是该元素出现的最后一个索引。

示例

其代码为 -

现场演示

const arr = [1, 6, 3, 1, 3, 1, 6, 3];
const removeOddOccurence = (arr =[]) => {
   // keeping the original array unaltered
   const copy = arr.slice();
   const map = {};
   arr.forEach((num, ind) => {
      if(map.hasOwnProperty(num)){
         map[num][0]++;
         map[num][1] = ind;
      }else{
         map[num] = [1, ind];
      };
   });
   for(const key in map){
      const [freq, index] = map[key];
      if(freq !== 1 && freq % 2 === 1){
         copy.splice(index, 1, '');
      };
   };
   return copy.filter(el => el !== '');
};
console.log(removeOddOccurence(arr));

输出

控制台中的输出将是 -

[1, 6, 3, 1, 3, 6]

以上就是在 JavaScript 中从数组中删除任何数字/元素的奇数出现的详细内容.

返回顶部
顶部