Array duplicate removal for duplicates exceeding `N`-number I recently encountered a front-end interview coding challenge question that required one to create a function which returned an array that excluded numbers that occurred more than n-number of times (i.e. duplicate-removal).  In this example it was all numbers repeated &gt;= three (3) times.  I managed to submit an answer, but admittedly struggled solving it.
I am looking for any feedback / suggestions on how to make it more concise and efficient (the for loop inside the forEach method is especially repulsive).
Here is what I came up with:


// Remove duplicates that occur 3 or more times in an array
// keeping unique values and those with less than 3
function removeMany(arr) {
  const newArr = Array.from(arr).sort()
  let count = 0;
  let result = []

  newArr.forEach((value, index, ar) =&gt; {
    count += 1;
    // refactored afterwards from (ar[index + 1] !== value)
    if (ar.lastIndexOf(value) &lt;= index &amp;&amp; count &lt;= 2) {
      for (var i = 0; i &lt; arr.length; i++) {
        if (arr[i] === value) {
          result.push(arr[i])
        }
      }
      count = 0
    } else if (ar[index + 1] !== value) {
      count = 0;
    }
  });

  // +1 is there anyway to return a result that mimicks the original order of `numbers`?
  return result;  // [1, 2, 2, 3, 4, 4]
}

// Ex. 1
const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers));
As you expected, there is a much simpler way to do this. 


Create a map where the keys are the numbers in the array and the value is the number of times each number appears in the array.
Filter the input array for any numbers that appear less than X times.




function removeMany(numbers, max) {
    const numberMap = numbers.reduce((map, num) =&gt; {
        map[num] = map[num] ? map[num] + 1 : 1;
        return map;
    }, []);
    
    return numbers.filter(num =&gt; numberMap[num] &lt; max);
}

const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers, 3));