0

Hi there,

why does the sort function not sort out numeric values depending on their values(large to small or small to large)?

var drinks1 = [40,30,10,20,100];

println(drinks1.sort());  // this will give you  10, 100, 20, 30, 40

it sorts those values as follows: 10,100,20,30,40

Is there a way of changing the order that the function works in?

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by pritaeas
1

sort does a string comparison by default. You can specify a sort function as parameter to the function. The compare function takes two parameters, and should return an number. Negative means the first is smaller than the second, zero means equal, and positive means the second is smaller.

function compare(x, y) {
    return x - y;
}

println(drinks1.sort(compare));

Edited by pritaeas

Votes + Comments
Thanks, I'm appreciate that function. Never tried it before.
0

println(drinks1.sort(compare));

Aren't you supposed to pass parameter values to the compare function?

0

Aren't you supposed to pass parameter values to the compare function?

No. You only provide the callback function, the sort function then passes the two parameters to that function.

Edited by pritaeas

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.