0

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!

kera
  • 9
  • 1
  • 1
  • 2
    Possible duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Prasanna Venkatesh Aug 17 '17 at 12:44
  • Your questions is not clear. Do you want to compare 2 arrays see if their contents are the same? Are you searching if an element of array1 exists in array2? if yes; Are the index locations relevant? – Ulug Toprak Aug 17 '17 at 12:57

2 Answers2

1

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>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
0
$(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]);
                }
            }


        });