Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Understanding an array function 1

Status
Not open for further replies.

kzn

MIS
Jan 28, 2005
209
GB
Hi

I am having problems with the following code. I do not understand how this actually works. I have spent ages going through it. It is used to sort a numeric array as the normal sort would put the array into the following 1,10,12,2. I do not understand the var1 and var2.

function numSort(var1,var2) {
return var1-var2;
}

array1 = new Array(1,2,10,12);
array2 = array1.sort(numSort);


Any help appreciated.

Thank you
 
I am a little confused by your statement. Are you interested in knowing why you are using numSort with var1 and var2? Or are you not getting the array to sort properly?

In regards to the var1 & var2 question, sort() will sort the array alphabetically or in dictionary order. However, if you want to sort the array numerically, you will need to have a function just like numSort. What this does is take var1 and compare it to var2 to see what the relationship is between the two. There are three possible return values:
< 0: Sort var1 to be a lower index than var2
Zero: var1 and var2 are equal value.
> 0: Sort var2 to be a lower index than var1

I would also recommend wrapping the return statement in parenthesis like:
Code:
function numSort(var1,var2) {
    return (var1 - var2);
}

Hope this helps!
 
Thank you MikeyJudd

My book gave no explanation for what it was doing ... now I understand. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top