Remove all items from array

Benchmark created by Vojta 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(src, remove) {
    var result = [],
        i = j = 0;
  
    while (i < remove.length) {
      while (remove[i] !== src[j]) {
        result.push(src[j++]);
      }
  
      i++;
      j++;
    }
  
    while (j < src.length) {
      result.push(src[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.