A couple of useful features

    Somehow I needed to make an array of unique elements in javascript. Sincerely believing in the power of jQuery, I began to look for the necessary opportunity in the manual, but did not find anything useful. Because I really needed this feature, I had to write a function myself.

    Array.prototype.unique = function () {
    var nArray = new Array;
    for (i = 0; i <= this.length-1; i ++) {
    if (! nArray.contains (this [i])) {
    nArray.length + = 1;
    nArray [nArray.length-1] = this [i];
    }
    }
    return nArray;
    }

    Array.prototype.contains = function (val) {
    for (j = 0; j <= this.length-1; j ++) {
    if (this [j] == val) return true;
    }
    return false;
    } * This source code was highlighted with Source Code Highlighter .


    unique - returns a new array consisting of unique elements;
    contains - checks for the presence of the specified element in the array. In general, this function is necessary for the first to work, but can be used separately.

    That's probably all :)

    PS
    If something like this has already appeared on Habré, then please write about this in the comments. I am also pleased to read your wishes and suggestions.

    Also popular now: