Relative Complement of B in A with Integer Arrays

Benchmark created by S on


Description

Theory: Array.filter() will be faster than nested jQuery.grep() when using arrays of integers

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

// jquery grep functionized
    if (!Array.prototype.subtractSet) {
      Array.prototype.subtractSet = function (set, key) {
    return $.grep(this, function (a) {
        return $.grep(set, function (b) {
            return key ? b[key] === a[key] : a === b;
        }).length == 0;
    });
      }
    }
    
    
    
    
    // the following code courtesy Andy @ Stack Overflow
        // pass in an array and the key for which you want values
        // it returns an array of those values
        function getValues(arr, key) {
          return arr.map(function (el) { return el[key]; });
        }
        
    if (!Array.prototype.notFoundIn) {
      Array.prototype.notFoundIn = function (inThisArray, key) {
        var thisArr = key ? getValues(this, key) : this;
        var arrIn = key ? getValues(inThisArray, key) : inThisArray;
        return thisArr.filter(function (el) {
          return arrIn.indexOf(el) === -1;
        });
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
nested jQuery.grep()
var foundBuildings = $.grep([1, 2, 3], function (a) {
    return $.grep([2], function (b) {
        return b == a;
    }).length == 0;
}); // [1, 3]
ready
mapped Array.filter() (not mapped in this case)
[1, 2, 3].notFoundIn([2]); // [1, 3]
ready
jQuery.grep() subtract set
[1, 2, 3].subtractSet([2]); // [1, 3]
ready

Revisions

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