kera
kera

Reputation: 9

How to compare the content of two arrays in jQuery?

I have two arrays and I want to compare the content of array1 with array2.

var array1 = ['test1','test2','test3','test4'];
var array2 = ['test2','test3'];

And only if array1 matches array2 (like test2 == test2) then it should do something. So in this case it should iterate over the two arrays, but only do something for test2 and test3.

Thank you for your answers!

Upvotes: 0

Views: 2893

Answers (2)

Zaigham Sarfaraz
Zaigham Sarfaraz

Reputation: 111

$(document).ready(function () {

            var array1 = ['test1', 'test2', 'test3', 'test4'];
            var array2 = ['test2', 'test3'];

            for (var i = 0; i < array1.length; i++) {

                if($.inArray(array1[i], array2) > -1)
                {
                    alert(array1[i]);
                }
            }


        });

Upvotes: 0

Milan Chheda
Milan Chheda

Reputation: 8249

You can use $.grep followed by $.inArray():

var array1 = ['test1', 'test2', 'test3', 'test4'];
var array2 = ['test2', 'test3', 'test5'];
var unique = $.grep(array2, function(element) {
  if ($.inArray(element, array1) !== -1) {
    console.log(element)
    // do something here...
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions