Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Numeric Sort

By default, the sort() function sorts values as strings, which is suitable for string comparisons (e.g., “Apple” comes before “Banana”).

However, when sorting numbers as strings, “25” would be considered greater than “100” because “2” is greater than “1”.

To address this issue, you can provide a comparison function to the sort() method.

Example

const points = [40100152510];
points.sort(function(a, b){return a – b});

Apply the same technique to sort an array in descending order.

Example

const points = [40100152510];
points.sort(function(a, b){return b – a});