How to remove some items from array when there is repetition in JavaScript

In JavaScript, you may need to remove items from an array that appear in multiples of three (triplets). This is useful when you want to keep only the remaining elements after removing complete sets of triplets.

Understanding the Problem

The goal is to remove triplets (groups of 3 identical elements) from an array and keep only the remaining elements. For example, if an array has 5 occurrences of the number 1, we remove 3 of them (one triplet) and keep 2.

Solution Implementation

const arr1 = [1,1,1,3,3,5];
const arr2 = [1,1,1,1,3,3,5];
const arr3 = [1,1,1,3,3,3];
const arr4 = [1,1,1,1,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,7,7];

const removeTriplets = arr => {
    const hashMap = arr => arr.reduce((acc, val) => {
        if(val in acc){
            acc[val]++;
        }else{
            acc[val] = 1;
        };
        return acc;
    }, {});
    
    let res = [];
    let obj = hashMap(arr);
    
    for(let key in obj){
        for(let i = 0; i 

[ '3', '3', '5' ]
[ '1', '3', '3', '5' ]
[]
[ '1', '7', '7' ]

How It Works

The solution uses a two-step process:

  1. Count occurrences: The hashMap function counts how many times each element appears in the array
  2. Keep remainders: For each element, we use modulo operator (% 3) to find how many elements remain after removing complete triplets

Alternative Approach Using Map

const removeTriplets2 = arr => {
    const count = new Map();
    
    // Count occurrences
    arr.forEach(item => {
        count.set(item, (count.get(item) || 0) + 1);
    });
    
    const result = [];
    
    // Keep remainders after removing triplets
    for(let [key, value] of count){
        const remainder = value % 3;
        for(let i = 0; i 

[ 1, 3 ]

Key Points

  • The function returns string values because object keys are converted to strings
  • If you need numeric values, use parseInt(key) when pushing to the result array
  • Complete triplets are effectively removed, leaving only the remainder elements
  • Empty array is returned when all elements form complete triplets

Conclusion

This approach efficiently removes triplets by counting occurrences and keeping only the remainder after dividing by 3. The modulo operator is key to determining how many elements to retain after removing complete sets of three.

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

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements