Array.diff

Posted by & filed under javascript.

Just had some fun with Javascript (and Prototype):

/**
 * Will return those elements which are added in cmp
 * @author Michael Jostmeyer
 * @param {Array} cmp
 * @return {Array}
 */
Object.extend(Array.prototype, {
    diff: function(cmp) {
    var res=[], resi=0, neq, cmpi=cmp.length, thisi, thisl = this.length;
    while (cmpi--) {
        thisi=thisl;
        while (thisi-- && (neq = cmp[cmpi] !== this[thisi]));
        neq && (res[resi++] = cmp[cmpi]);
    }
    return res;
}});

With this you are able to get those values which are additionaly in the cmp-Array. These values are returned in a new Array.

var a = [1,2,3,5,6]; var b = [1,3,5,7,9];
var x = a.diff(b);
//x=[9, 7]
var y = b.diff(a)
//y=[6, 2]

Enjoy it! 😉

Leave a Reply