unique in array (v22)

Preparation HTML

``````<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Setup

``````var arr = [0,1,2,3,4,5,'a','b','c','d','e','f','g','h','i','j',
0,1,2,3,4,0,1,3,5,0,7,1,'f','h','c','a','b',0,1,5];

var arrclone1 = [0,1,2,3,4,5,'a','b','c','d','e','f','g','h','i','j',
0,1,2,3,4,0,1,3,5,0,7,1,'f','h','c','a','b',0,1,5];
var arrclone2 = [0,1,2,3,4,5,'a','b','c','d','e','f','g','h','i','j',
0,1,2,3,4,0,1,3,5,0,7,1,'f','h','c','a','b',0,1,5];
var arrclone3 = [0,1,2,3,4,5,'a','b','c','d','e','f','g','h','i','j',
0,1,2,3,4,0,1,3,5,0,7,1,'f','h','c','a','b',0,1,5];

var jqFilter = function(v, k){
return \$.inArray(v ,arr) === k;
}

Array.prototype.unique = function() {
var a = [];
for (var i=0, l=this.length; i<l; i++)
if (a.indexOf(this[i]) === -1)
a.push(this[i]);
return a;
}

Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}

function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}

Array.prototype.sortFilter = function() {
var sorted_arr = this.sort();
var results = [];
for (var i = 0; i < this.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}

Array.prototype.sortUnique = function() {
this.sort();
var last_i;
for (var i=0;i<this.length;i++)
if ((last_i = this.lastIndexOf(this[i])) !== i)
this.splice(i+1, last_i-i);
return this;
}``````

Test runner

Testing in
TestOps/sec
jQuery grep
``\$.grep(arr, jqFilter);``
Underscore uniq
``_.uniq(arr)``
My arr.unique
``arr.unique();``
Rafael's arr.getUnique
``arr.getUnique();``
TLindig's filter
``arrclone1.filter(onlyUnique);``
``arrclone2.sortFilter();``
``arrclone3.sortUnique();``
``arr.unique().sort();``