Saturday, May 24, 2014

Removing duplicates in a javascript array

I was looking at this today and discovered grep.

$(function () {

    var myOriginalValues = [1, 3, 7, 3, 3, 9, 2];
    var res = [];

    $.each(myOriginalValues, function (i, el) {
        if ($.inArray(el, res) === -1) res.push(el);
    });

    // Now a grep version
    var grepVersion = function(arr){
        return $.grep(arr,function(v,k){
            return $.inArray(v, arr) === k;
        })
    };

    var arr = ['tree',2,4,5,4,1,1,3,3,5, 'tree', 'hat']
    var x = grepVersion(arr);

});





Javascript This keyword

This is a variable that is available when you use functions, and depending on how the function was invoked This can be different things.


// This - will be global scope
function myFunction() {
    console.log('This is a lot of stuff:');
    console.log(this);
}

// This - will be the myThing object
var myThing = { name: 'john', age: 21};
myThing.doStuff = function(){
    console.log(this);
    console.log(this.name);
};

// This function outputs:
// { name: 'john', age: 21, doStuff: [Function] }
// john


(function doTheFunctions(){
    myFunction();
    myThing.doStuff();
})();