Tests:
  • original duplicate removal

    x
     
    // 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) => {
        count += 1;
        // refactored afterwards from (ar[index + 1] !== value)
        if (ar.lastIndexOf(value) <= index && count <= 2) {
          for (var i = 0; i < 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]
    }
    const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
    console.log(removeMany(numbers));
  • 2-pass approach

     
     // Remove duplicates that occur 3 or more times in an array
        // keeping unique values and those with less than 3
        function removeMany(arr) {
          let countMappings = arr.reduce(function(carry, item) {
              if (carry[item]!== undefined) {
                carry[item]++;
              }
              else {
                carry[item] = 1;
              }
              return carry;
          }, {});
          return arr.reduce(function(final, item) {
            if (countMappings[item] <3) {
              final.push(item);
            }
            return final;
          }, []);
        }
        const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
        console.log(removeMany(numbers));
  • 2-pass with filtering

     
    function removeMany(numbers, max) {
        const numberMap = numbers.reduce((map, num) => {
            map[num] = map[num] ? map[num] + 1 : 1;
            return map;
        }, []);
        
        return numbers.filter(num => numberMap[num] < max);
    }
    const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
    console.log(removeMany(numbers, 3));
Rendered benchmark preparation results:

Suite status: <idle, ready to run>

Previous results

Experimental features:

  • Test case name Result
    original duplicate removal
    2-pass approach
    2-pass with filtering

    Fastest: N/A

    Slowest: N/A

Latest run results:
Run details: (Test run date: 5 years ago)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
Chrome 75 on Mac OS X 10.13.6
View result in a separate tab
Test name Executions per second
original duplicate removal 44283.3 Ops/sec
2-pass approach 43351.4 Ops/sec
2-pass with filtering 44605.8 Ops/sec