1

Possible Duplicate:
Using jQuery to compare two arrays

I need a Javascript or jQuery function to determine if an array contains all the values of another array. The second array can have more values than the first.

This should return either true or false. For example.

comparing  array1 = [1,2,3]  and  array2 = [1,2]      should return false

comparing  array1 = [1,2,3]  and  array2 = [1,1,2]    should return false

comparing  array1 = [1,2,3]  and  array2 = [3,2,1]    should return true

comparing  array1 = [1,2,3]  and  array2 = [1,2,1,3]  should return true

Performance is not a concern. Thanks!

2

2 Answers 2

1

Checks each element in the first array and sees if it exists in the second array.

NB. This is pure javascript, might be an easier way in jQuery.

var notFound = false;

for(var i = 0, len = firstArray.length; i < len; i++){
    if(secondArray.indexOf(firstArray[i]) === -1)
    {
         notFound = true;
         break;
    }
}

if(notFound)
{
    ....
}
Sign up to request clarification or add additional context in comments.

2 Comments

Something I just discovered, probably obvious to those with more programming skill is that this will return false if the values in the arrays are different types. I had to add a parseFloat() conversion in creating the second array to make sure both arrays contained numbers.
This post has some useful information about the uses of === and what it will fail on. stackoverflow.com/questions/359494/… My solution was purely for primitive int types, I can't guarantee it will work for objects, strings etc
0

Update: had read the question too fast, following only works if in same order

function same_elements(array1, array2){  
  var result = true; 
  $(array1).each(function(index, value) {
    if (value != array2[index]) {result = false};
  });
  return result;
}

2 Comments

This doesn't work for array1 = [1,2,3] and array2 = [1,2,1,3]
yeah, just realized the unordered case

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.