- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the least duplicate items in an array JavaScript
We are required to write a JavaScript function that takes in an array of literals which may contain some duplicate values.
The function should return an array of all those elements that are repeated for the least number of times.
For example− If the input array is −
const arr = [1,1,2,2,3,3,3];
Then the output should be −
const output = [1, 2];
because 1 and 2 are repeated for the least number of times (2)
Example
const arr = [1,1,2,2,3,3,3]; const getLeastDuplicateItems = (arr = []) => { const hash = Object.create(null); let keys, min; arr.forEach(el => { hash[el] = hash[el] || { value: el, count: 0 }; hash[el].count++; }); keys = Object.keys(hash); keys.sort(function (el, b) { return hash[el].count - hash[b].count; }); min = hash[keys[0]].count; return keys. filter(el => { return hash[el].count === min; }). map(el => { return hash[el].value; }); } console.log(getLeastDuplicateItems(arr));
Output
And the output in the console will be −
[ 1, 2 ]
Advertisements