SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: comparing arrays
-
May 13, 2008, 14:54 #1
- Join Date
- Oct 2005
- Location
- London
- Posts
- 1,678
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
comparing arrays
Hi,
I have two arrays( as a result of the user dragging some elements into droppable zones --using scriptaculous). The first array is specified by me in the javascript code and represents the correct answers and the second one is dynamically created by the user trying to get the correct answers.
I need to compare the arrays. All i need to know is if array 1 contains the same values as array 2. This sounds simple...i thought i'd just check that the arrays were the same length:
Code JavaScript:if (arr1.length != arr2.length) return false;
and then continue with iterating over the array:
Code JavaScript:(arr1[i] != arr2[i]) return false;
Now this would work fine only if i could guarantee that my second array (the one generated from the users answers) was going to be in the same order as the other one. Invariably it won't be because i've let them drag the elements in any order.
So how do i compare two arrays like this? Is there any way to sort the dyanically generated array so it starts with the lowest value first or is there a way to compare two arrays even if their order doesn't match.
-
May 13, 2008, 15:04 #2
- Join Date
- Oct 2005
- Location
- London
- Posts
- 1,678
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Sorry, solved i think....
using array.sort(); seems to give me the array back in order of the lowest values first...although my reference says it orders lexicographically...so if my array went in to double figures then 10 would appear before 1.
any suggestions welcome!
-
May 13, 2008, 16:52 #3
- Join Date
- Jan 2007
- Location
- Christchurch, New Zealand
- Posts
- 14,729
- Mentioned
- 104 Post(s)
- Tagged
- 4 Thread(s)
You can provide a custom sort function.
Code javascript:array.sort(function(a, b) { return a - b; });
Further details can be found at http://developer.mozilla.org/en/docs...cts:Array:sortProgramming Group Advisor
Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
Car is to Carpet as Java is to JavaScript
-
May 14, 2008, 06:54 #4
- Join Date
- Oct 2005
- Location
- London
- Posts
- 1,678
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yes. I've found that! Thankyou
Bookmarks