
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Items from Array with Repetition in JavaScript
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' ]
Advertisements