Suppose we have an array of numbers like this -
const arr = [1, 6, 3, 1, 3, 1, 6, 3];
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.
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];
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.
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));
The output in the console will be-
[1, 6, 3, 1, 3, 6]
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!