filter versus dictionary (v3)

Revision 3 of this benchmark created on


Setup

var array = [{"name":"Joe", "age":17}, {"name":"Bob", "age":17}, {"name":"Carl", "age": 35}];
    
    function uniqueBy(arr, fn) {
      var unique = {};
      var distinct = [];
      arr.forEach(function (x) {
        var key = fn(x);
        if (!unique[key]) {
          distinct.push(key);
          unique[key] = true;
        }
      });
      return distinct;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
map
var ages = array.map(function(obj) { return obj.age; });
ages = ages.filter(function(v,i) { return ages.indexOf(v) == i; });
ready
dictionary
var unique = {};
var distinct = [];
    for( var i in array ){
     if( typeof(unique[array[i].age]) == "undefined"){
      distinct.push(array[i].age);
     }
     unique[array[i].age] = 0;
    }
ready
dictionary with forEach
var unique = {};
var distinct = [];
array.forEach( function(x){if(!unique[x.age]) {distinct.push(x.age);unique[x.age]=true;}})
ready
generic func using dictionary with forEach
uniqueBy(array, function(x){return x.age;});
ready

Revisions

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