Originally published byDev.to
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]
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}
- 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.
🇺🇸
More news from United StatesUnited States
NORTH AMERICA
Related News

Master Local Fine-Tuning with "gemma-trainer"
8h ago
Building a Plugin-Free Newsletter Popup on WordPress: Custom REST Endpoint Mailchimp API v3
8h ago
ภาษาโปรแกรมมิ่งที่ syntax ง่าย ทำให้ AI หลอนน้อยลง จริงหรือ?
8h ago
How I Built a File-Timestamp-Based Feedback Loop to Enforce AI Output Quality
8h ago
GitHub Trending Digest — 2026-07-07
9h ago