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 ]

Updated on: 21-Nov-2020

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements