fooDigi Posted March 8, 2007 Share Posted March 8, 2007 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. Quote Link to comment Share on other sites More sharing options...
warewolfe Posted March 8, 2007 Share Posted March 8, 2007 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.