Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find common elements only between 2 arrays in jquery [duplicate]

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.

  1. If every elements of both arrays are equal then show a message/alert. e.g. "All records already existing."

  2. If every elements of both the arrays are different then just add them all in a "VAR", e.g. var resultset = .... (where 7,8,9 will stored)

  3. If few elements common between two arrays then for the common elements show a message with element, e.g. "Record 1,2,3,4,5,6 are already exists" and add the different elements in "VAR", e.g. var resultset = .... (where 7,8,9 will stored). Both the message and difference elements collection will perform at the same time.

like image 271
Monibrata Avatar asked Mar 04 '14 04:03

Monibrata


3 Answers

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];
like image 110
Sudharsan S Avatar answered Sep 28 '22 08:09

Sudharsan S


Here is my version

function diff(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);
    }
like image 45
redV Avatar answered Sep 28 '22 10:09

redV


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 = new Set(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/

like image 33
jfriend00 Avatar answered Sep 28 '22 10:09

jfriend00