filter versus dictionary (v18)

Revision 18 of this benchmark created on


Setup

var array = [{
      "name": "Joe",
      "age": 17
    }, {
      "name": "Bob",
      "age": 17
    }, {
      "name": "Carl",
      "age": 35
    }];

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
for loop inline assignment
var unique = {};
var distinct = [];
for (var i = 0, entitytype; entitytype = array[i++];) {

  if (typeof(unique[entitytype.age]) == "undefined") {
    distinct.push(entitytype.age);
  }
  unique[entitytype.age] = 0;
}
ready
Single loop (implicit object undefined check)
var unique = {}, distinct = [],
  entitytype, i;
for (i = 0; i < array.length; i++) {
  entitytype = array[i++];
  if (!unique[entitytype.age]) {
    distinct.push(entitytype.age);
  }
  unique[entitytype.age] = {};
}
ready
Reduce
distinct = array.reduce(function(distinctValues, obj) {
  if (distinctValues.indexOf(obj.age) === -1) {
    distinctValues.push(obj.age)
  }
  return distinctValues;
}, []);
ready
dictionary return whole object
function uniqueBy(arr, fn) {
  var i, len, key, unique, distinct;
  unique = {};
  distinct = [];
  for (i = 0, len = arr.length; i < len; i += 1) {
    key = fn(arr[i]);
    if (!unique[key]) {
      distinct.push(arr[i]);
      unique[key] = true;
    }
  }
  return distinct;
}

uniqueBy(array, function(item) {
  var i, len, keys, key;
  keys = Object.keys(item);
  key = '';
  for (i = 0, len = keys.length; i < len; i += 1) {
    key += item[keys[i]];
  }
  return key;
})
ready
Set
const distinct = [...new Set(array.map(a => a.age))]
ready
map one-line
const ages = array
	.map(obj => obj.age)
	.filter((v, i, a) => a.indexOf(v) == i);
ready

Revisions

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