JavaScript array: Find all elements that appear more than n times

JavascriptWeb DevelopmentObject Oriented Programming

We have an array of Number/String literals that contains some repeated entries. Our job is to write a function that takes in a positive integer Number n and returns a subarray of all the elements that makes appearance more than or equal to the number n specified by the only argument.

Therefore, let's write the code for this function −

We will use a Map() to keep count of the frequency of elements and later return the elements that exceed the specified count. The code for this will be −

Example

const arr = [34, 6, 34, 8, 54, 7, 87, 23, 34, 6, 21, 6, 23, 4, 23];
const moreThan = (arr, num) => {
   const creds = arr.reduce((acc, val) => {
      let { map, res } = acc;
      const count = map.get(val);
      if(!count && typeof count !== 'number'){
         map.set(val, 1);
      }else if(num - count <= 1){
         res.push(val);
      } else {
         map.set(val, count+1);
      };
      return {map, res};
   }, {
      map: new Map(),
      res: []
   });
   return creds.res;
};
console.log(moreThan(arr, 3));

Output

The output in the console will be −

[34, 6, 23]
raja
Published on 31-Aug-2020 06:44:04
Advertisements