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!

2
  • 2
    Possible duplicate of How to compare arrays in JavaScript? Commented Aug 17, 2017 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? Commented Aug 17, 2017 at 12:57

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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]);
                }
            }


        });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.