Removing the odd occurrence of any number/element from an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose, we have an array of numbers like this −

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

We are required to write a JavaScript function that takes in one such array as the first and the only argument. Then the function should look for all such numbers in the array that appear for an odd number of times (excluding only once).

For example,

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

And the output array should look like −

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

We will prepare a hashmap to keep track of occurrences of each number, and at last we will iterate over the map to delete the last occurence of that number that appears for an odd number of times.

Each key in our map will hold an array value, the first element of which will be the number of times that element have appeared and second will be the last index at which it appeared.

Example

The code for this will be −

 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));

Output

And the output in the console will be −

[1, 6, 3, 1, 3, 6]
raja
Published on 22-Feb-2021 09:33:03
Advertisements