Deleting occurrences of an element if it occurs more than n times using JavaScript


In the realm of JavaScript programming, effectively managing the occurrences of elements within an array is of paramount importance. Specifically, the ability to delete instances of an element if it surpasses a certain threshold, denoted by the variable "n," can greatly enhance the efficiency and accuracy of data manipulation tasks. By harnessing the power of JavaScript, developers can employ a robust approach to selectively remove redundant element occurrences from arrays. In this article, we will embark on a comprehensive exploration of the step-by-step process for deleting occurrences of an element if it occurs more than "n" times using JavaScript, elucidating the intricacies of the underlying algorithms and empowering programmers to optimize their code for increased productivity.

Problem Statement

Given an array of integers and a positive integer n, write a JavaScript function that deletes all occurrences of any element in the array if it occurs more than n times. The function should modify the input array in-place and return the modified array.

Sample Input −

const arr = [1, 2, 3, 1, 2, 1, 1, 3];
const n = 2;

Sample Output −

[1, 2, 3, 1, 2, 3]

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Using a Hash Map

  • Using an Array to Track Occurrences

  • Using a Frequency Map

Method 1: Using a Hash Map

To create a hash map, begin with an empty object. Proceed by iterating through the input array. During each iteration, determine if the element exists as a key within the hash map. If it does not, add it as a new key and set its value to 1. Alternatively, if the element already exists, increment its corresponding value. Afterward, iterate through the input array once more, filtering out elements whose count exceeds a given threshold, represented by 'n', based on the hash map. Ultimately, return the resulting filtered array.

Example

The function deleteOccurrences takes an array arr and a number n as input. It initializes an empty object countMap to serve as a hash map. The forEach method iterates over arr, checking if each element num exists as a key in countMap. If not, it adds num as a key and sets its value to 1. If it exists, it increments its value by 1. After creating the hash map, the filter method is used on arr to create a new array that includes elements whose count (according to countMap) is less than or equal to n. Finally, the filtered array is returned as the result.

function deleteOccurrences(arr, n) {
   const countMap = {};
   arr.forEach((num) => {
      countMap[num] = (countMap[num] || 0) + 1;
   });
   return arr.filter((num) => countMap[num]-- <= n);
}
const arr = [1, 2, 4, 2, 2, 1, 3, 2, 1];
const n = 2;
console.log(deleteOccurrences(arr, n));

Output

The following is the console output −

[ 4, 2, 1, 3, 2, 1 ]

Method 2: Using an Array to Track Occurrences

To compress the code, we start by initializing an empty array to store element occurrences. Then, we iterate over the input array, checking the count of occurrences in the result array for each element. If the count is less than or equal to n, we add the element to the result array. Finally, we return the result array.

Example

The function deleteOccurrences takes an array arr and a number n as input. It creates an empty array called result to store elements that appear less than or equal to n times. Using the forEach method, it iterates over arr and checks the count of occurrences in result using the filter method. If the count is less than n, it adds the element to result. Finally, it returns result as the output.

function deleteOccurrences(arr, n) {
   const result = [];
   arr.forEach((num) => {
      if (result.filter((el) => el === num).length < n) {
         result.push(num);
      }
   });
   return result;
}
const arr = [1, 2, 4, 2, 2, 1, 3, 2, 1];
const n = 2;
console.log(deleteOccurrences(arr, n));

Output

The following is the console output −

[ 1, 2, 4, 2, 1, 3 ]

Method 3: Using a Frequency Map

Firstly, initialize an empty map to keep track of element frequencies. Then, proceed to iterate over the input array, incrementing the frequency of each element in the map. Afterwards, create a new array by iterating over the input array once more, selecting only the elements whose frequency is less than or equal to a given value, n. Finally, return the resulting new array, which contains only those elements satisfying the frequency condition.

Example

The function deleteOccurrences takes an array arr and a number n as input. It initializes an empty Map called frequencyMap to store the frequency of elements. It iterates over arr using the forEach method and checks if each element num is a key in frequencyMap. If it doesn't exist, it sets its value to 1; otherwise, it increments its value by 1. After creating the frequency map, it filters the input array arr using the filter method, creating a new array that includes only elements with a frequency less than or equal to n according to frequencyMap. Finally, the filtered array is returned as the result.

function deleteOccurrences(arr, n) {
   const result = [];
   arr.forEach((num) => {
      if (result.filter((el) => el === num).length < n) {
         result.push(num);
      }
   });
   return result;
}
const arr = [1, 2, 4, 2, 2, 1, 3, 2, 1];
const n = 2;
console.log(deleteOccurrences(arr, n));

Output

The following is the console output −

[ 1, 2, 4, 2, 1, 3 ]

Conclusion

In culmination, the process of eliminating instances of an element exceeding a certain threshold in JavaScript can be efficiently accomplished. By harnessing the power of conditional statements and array manipulation, one can effectively traverse and modify arrays to remove excessive occurrences of a specific element. Although this task may seem arduous at first, the judicious application of these techniques empowers developers to curtail redundancy and streamline data structures. Employing such strategies in JavaScript programming can substantially optimize performance and promote code elegance, fostering a more seamless and expedient user experience.

Updated on: 04-Aug-2023

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements