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?

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));
commented: Thanks, I'm appreciate that function. Never tried it before. +8

println(drinks1.sort(compare));

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.