DEV Community

Cover image for Javascript Array sort method challenges
karthika jasinska
karthika jasinska

Posted on

Javascript Array sort method challenges

Numeric Sort
By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting numbers.

You can fix this by providing a compare function:

const points = [40, 100, 1, 5, 25, 10];
let res=points.sort((a, b)=>{return a - b});
console.log(res);//ascending order
let res1=points.sort((a, b)=>{return b - a});
console.log(res1);//descending order

//output:
//[1,5,10,25,40,100]
//[100,40,25,10,5,1]
Enter fullscreen mode Exit fullscreen mode

The Compare Function
The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value, depending on the arguments:

function(a, b){return a - b}

Enter fullscreen mode Exit fullscreen mode
  • The sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
  • If the result is negative, a is sorted before b.
  • If the result is positive, b is sorted before a.
  • If the result is 0, no changes are done with the sort order of the two values.

Top comments (0)