Geeks With Blogs
Liam McLennan hackingon.net

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

Posted on Thursday, March 11, 2010 3:35 PM | Back to top

Copyright © Liam McLennan | Powered by: GeeksWithBlogs.net