Handy Javascript array Extensions – distinct()
- by Liam McLennan
The following code adds a method to javascript arrays that returns a distinct list of values. Array.prototype.distinct = function() {
var derivedArray = [];
for (var i = 0; i < this.length; i += 1) {
if (!derivedArray.contains(this[i])) {
derivedArray.push(this[i])
}
}
return derivedArray;
};
and to demonstrate:
alert([1,1,1,2,2,22,3,4,5,6,7,5,4].distinct().join(','));
This produces 1,2,22,3,4,5,6,7