Array unique

Benchmark created by Øyvind Sean Kinsey on


Description

@wolframkriesing wondered what the most efficient unique function for Array would be: http://twitter.com/wolframkriesing/status/83847205189980160

Let’s find out!

Preparation HTML

<script>
  var array = [1, 2, 3, 4, 2, 3, 4, 5, 6, 7, 2, 3, 4, 1, 2, 3, 4, 2, 3, 4, 5, 6, 7, 2, 3, 4];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using indexOf - O(n2)
array.filter(function(e, i, arr) {
  return arr.slice(0, i).indexOf(e) == -1;
});
ready
Using indexOf and ~ - O(n2)
array.filter(function(e, i, arr) {
  return !~arr.slice(0, i).indexOf(e);
});
ready
Using a map - O(n)
array.filter(function() {
  var seen = {};
  return function(e, i, arr) {
    return !(e in seen) && (seen[e] = 1);
  };
}());
ready
Using sort and filter - O((n lg n) + n)
array.sort().filter(function(e, i, arr) {
  return e !== arr[i - 1]
});
ready

Revisions

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