Remove all items from array (v2)

Revision 2 of this benchmark created on


Description

  • We have two arrays: A, B.
  • B is subset of A.
  • Items in both arrays have the same order.
  • Function returns A - B

Preparation HTML

<script>
  // basic version
  function removeAll(src, remove) {
    for (var i = 0; i < remove.length; i++) {
      src.splice(src.indexOf(remove[i]), 1);
    }
    return src;
  }
  
  // this should performs better, especially when removing more items
  function removeAllOptimized(array, toRemove) {
        // Handle a simple value
        if (toRemove && ! Object.prototype.toString.call(toRemove) === "[object Array]") {
                toRemove = [ toRemove ];
        }

        var result = [];
        var i = 0, j = 0;

        while (i < toRemove.length) {
                while (toRemove[i] !== array[j]) {
                        result.push(array[j++]);
                }

                i++;
                j++;
        }

        while (j < array.length) {
                result.push(array[j++]);
        }

        return result;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Basic
removeAll(
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  [2, 3, 4, 5, 6, 7, 10, 11, 13, 14, 16, 17, 19]);
ready
Optimized
removeAllOptimized(
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  [2, 3, 4, 5, 6, 7, 10, 11, 13, 14, 16, 17, 19]);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.