Jump to content

array comparison


fooDigi

Recommended Posts

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
https://forums.phpfreaks.com/topic/41733-array-comparison/#findComment-202450
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.