Jump to content

array comparison


fooDigi

Recommended Posts

i need to compare two arrays and see if one array has all the same values as the next...

 

example...

 

array1 has values 1,2,3,4,5

 

array2 has values 1,6,2,4,8,16,25,3,11,5

 

i want the comparison to return true since they have similar values (1,2,3,4,5)

 

thx for any help.

Link to comment
Share on other sites

Just some general ideas, first I don't know just how long your arrays will be so it may be a good idea to sort both arrays with. It may not matter.

 

  array1.sort;

  array2.sort;

 

then nest some for loops for comparison.

 

function arrayCompare(array1, array2)

{

var answer=false;

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

{

  var target=array1[ii];

  for(var jj=0;jj<array2.length;jj++)

  {

  var comparison=array2[jj];

  if(target == comparison)

  {

    array1.shift();//remove matching elements from the first array.

    break;// and get out of the loop.

  }   

  }//end jj for loop

}//end ii for loop

 

// if after removing all the matching elements in the first array

// the array length is zero then you've got a match.

if(array1.length <1)

{

  answer = true;

}

return answer;

}//end arrayCompare

 

Caveat

 

Please note I haven't actually tried this as I'm about to head to bed.

 

I don't know if you've considered what happens with multiple instances of numbers.

 

This will destroy the first array, if you want to keep it, send the function a copy of the original.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.