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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals. Our function should return a new array with all the triplets filtered.

The code for this will be −

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 < obj[key] % 3; i++){
         res.push(key)
      };
   }
   return res;
}

console.log(removeTriplets(arr1));
console.log(removeTriplets(arr2));
console.log(removeTriplets(arr3));
console.log(removeTriplets(arr4));

The output in the console −

[ '3', '3', '5' ]
[ '1', '3', '3', '5' ]
[]
[ '1', '7', '7' ]
raja
Updated on 09-Oct-2020 12:20:45

Advertisements