Wednesday 11 June 2014

Compare and remove array element - javascript 2

In this post we are going to see how to compare two array elements? and do something, when the element is matched.

This below prototype method will do that trick.
Array.prototype.diff = function(arr2) {
    this.sort();
    arr2.sort();
    for(var i = 0; i < this.length; i += 1) {
        if(arr2.indexOf( this[i] ) > -1){ 
            arr2.splice(arr2.indexOf( this[i] ), 1);
        }
    }
};
from the above code, first we are sorting both arrays. Then, We searching for index of same element occurred in both arrays.

arr2.indexOf( this[i] > -1)

If the first array element found in the arr2 array, It will return true. Inside the if block we can do whatever we want. In this post I'm just going to delete that matched element from arr2 array.

See this Example Demo. Go to the javascript tab and change your array and test it here itself.
var array1 = ['a', 'c','d','f','h'];
var array2 = ['a','b', 'c','d','e','f','g','h'];

//prototype method for array to find and remove matched element from argument array.
Array.prototype.diff = function(arr2) {
    this.sort();
    arr2.sort();
    for(var i = 0; i < this.length; i += 1) {
        if(arr2.indexOf( this[i] ) > -1){
            arr2.splice(arr2.indexOf( this[i] ), 1);
        }
    }
};

//code usage for above prototype method.
array1.diff(array2);

See the Demo below.
Have any doubt, feel free to comment here!

2 comments: