Home > Web Front-end > JS Tutorial > Remove odd occurrences of any number/element from array in JavaScript

Remove odd occurrences of any number/element from array in JavaScript

王林
Release: 2023-09-06 22:53:07
forward
1558 people have browsed it

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

Suppose we have an array of numbers like this -

const arr = [1, 6, 3, 1, 3, 1, 6, 3];
Copy after login

We need to write a JavaScript function that accepts an array like this as the first and only parameter. The function should then find all such numbers that occur an odd number of times (excluding just once) in the array.

For example,

In the above array, the numbers 1 and 3 both appear 3 times (an odd number), so our function should remove the third occurrence of these two numbers.

The output array should look like this -

const output = [1, 6, 3, 1, 3, 6];
Copy after login

We will prepare a hash map to keep track of the number of occurrences of each number, and finally we will iterate the map to remove the last occurrence of the odd number times that number.

Each key in the map will hold an array value where the first element is the number of occurrences of that element and the second element is the index of the last occurrence of that element.

Example

The code is -

Live demo

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));
Copy after login

Output

The output in the console will be-

[1, 6, 3, 1, 3, 6]
Copy after login

The above is the detailed content of Remove odd occurrences of any number/element from array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template