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

In JavaScript, managing array elements with excessive occurrences is a common data manipulation task. This article demonstrates how to delete elements that appear more than a specified number of times while preserving the original order.

Problem Statement

Given an array and a positive integer n, write a JavaScript function that removes elements if they occur more than n times. The first n occurrences should be kept, and any additional occurrences should be removed.

Sample Input:

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

Sample Output:

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

Method 1: Using a Hash Map

This approach uses an object to count occurrences and filters elements during iteration. It's efficient with O(n) time complexity.

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));
[ 1, 2, 4, 2, 1, 3 ]

Method 2: Using Array Counting

This method builds the result array by checking occurrences in real-time. It's simpler but less efficient for large arrays.

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));
[ 1, 2, 4, 2, 1, 3 ]

Method 3: Using Map Object

This approach uses JavaScript's Map object for cleaner frequency tracking and better performance with non-primitive keys.

function deleteOccurrences(arr, n) {
   const frequencyMap = new Map();
   const result = [];
   
   arr.forEach((num) => {
      const count = frequencyMap.get(num) || 0;
      if (count < n) {
         result.push(num);
         frequencyMap.set(num, count + 1);
      }
   });
   
   return result;
}

const arr = [1, 2, 4, 2, 2, 1, 3, 2, 1];
const n = 2;
console.log(deleteOccurrences(arr, n));
[ 1, 2, 4, 2, 1, 3 ]

Performance Comparison

Method Time Complexity Space Complexity Best For
Hash Map O(n) O(k) Large arrays
Array Counting O(n²) O(n) Small arrays
Map Object O(n) O(k) Mixed data types

Where n is array length and k is unique elements count

Conclusion

The hash map approach offers the best performance for most scenarios. Use the Map object method when working with complex data types, and consider the array counting method only for very small datasets where simplicity is preferred.

Updated on: 2026-03-15T23:19:00+05:30

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements