This is one idea of implementation:
Array.prototype.unique = function () {
unique_array = [];
for (var i = 0, l = this.length; i < l; i++) {
if(unique_array.indexOf(this[i]) == -1){
unique_array.push(this[i]);
}
}
return unique_array;
}
This version uses Object.keys which is a ECMAScript 5 only feature, as you can see on this website http://kangax.github.com/es5-compat-table/
Array.prototype.unique_e5 = function () {
unique_object = {};
for (var i = 0, l = this.length; i < l; i++) {
unique_object[this[i]] = 1;
}
return Object.keys(unique_object);
}
And this is how is done in prototype.js https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/array.js
/**
* Array#uniq([sorted = false]) -> Array
* - sorted (Boolean): Whether the array has already been sorted. If `true`,
* a less-costly algorithm will be used.
*
* Produces a duplicate-free version of an array. If no duplicates are
* found, the original array is returned.
*
* On large arrays when `sorted` is `false`, this method has a potentially
* large performance cost.
*
* ##### Examples
*
* [1, 3, 2, 1].uniq();
* // -> [1, 2, 3]
*
* ['A', 'a'].uniq();
* // -> ['A', 'a'] (because String comparison is case-sensitive)
**/
function uniq(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
array.push(value);
return array;
});
}
Also not that the prototype version uses the Prototype enumerable method include, which is:
/**
* Enumerable#include(object) -> Boolean
* - object (?): The object to look for.
*
* Determines whether a given object is in the enumerable or not,
* based on the `==` comparison operator (equality with implicit type
* conversion).
*
* ##### Examples
*
* $R(1, 15).include(10);
* // -> true
*
* ['hello', 'world'].include('HELLO');
* // -> false ('hello' != 'HELLO')
*
* [1, 2, '3', '4', '5'].include(3);
* // -> true ('3' == 3)
**/
function include(object) {
if (Object.isFunction(this.indexOf))
if (this.indexOf(object) != -1) return true;
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
}
Is there a better way to do it? faster or "better" cross browser compatible?
__proto__
.) \$\endgroup\$