Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
-
Count occurrences: The
hashMap function counts how many times each element appears in the array
-
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.
Advertisements
