Skip to content Skip to sidebar Skip to footer

How To Find Common Elements Only Between 2 Arrays In Jquery

var array1 = [1, 2, 3, 4, 5, 6]; var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; I have two arrays like above. Now I want to do the following in MVC 4 with jQuery. If every elements of

Solution 1:

Try this:

var array1  = [1, 2, 3, 4, 5, 6],
    array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var common = $.grep(array1, function(element) {
    return $.inArray(element, array2 ) !== -1;
});

console.log(common); // returns [1, 2, 3, 4, 5, 6];var array3 = array2.filter(function(obj) { return array1.indexOf(obj) == -1; });

// returns [7,8,9];

Solution 2:

Here is my version

functiondiff(arr1, arr2) {
        var obj = {}, matched = [],
            unmatched = [];
        for (var i = 0, l = arr1.length; i < l; i++) {
            obj[arr1[i]] = (obj[arr1[i]] || 0) + 1;
        }
        for (i = 0; i < arr2.length; i++) {
            var val = arr2[i];
            if (val in obj) {
                matched.push(val);
            } else {
                unmatched.push(val);
            }
        }
        // Here you can find how many times an element is repeating.console.log(obj);
        // Here you can find what are matching.console.log(matched);
        // Here you can check whether they are equal or not.console.log('Both are equal ? :' + 
        matched.length === a.length);
        // Here you can find what are different  console.log(unmatched);
    }

Solution 3:

If you do this kind of thing regularly, you may be interested in a Set object that makes this kind of stuff pretty easy:

var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var common = newSet(array1).intersection(array2).keys();

The open source Set object (one simple source file) is here: https://github.com/jfriend00/Javascript-Set/blob/master/set.js

Along with the intersection() method used here, it has all sorts of other set operations (union, difference, subset, superset, add, remove ...).

Working demo: http://jsfiddle.net/jfriend00/5SCdD/

Post a Comment for "How To Find Common Elements Only Between 2 Arrays In Jquery"