JavaScript
Sort numbers correctly in JavaScript
Pass a numeric comparator to Array.sort. Without one, JavaScript compares string representations, so 10 can appear before 2. Copy the array first when callers need the original order.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const original = [10, 2, 30, -1];
const sorted = [...original].sort((a, b) => a - b);
console.log(JSON.stringify(sorted));
console.log(JSON.stringify(original));How it works
A negative comparator result puts a before b; a positive result puts b first. Subtraction supplies the appropriate sign for ordinary finite numbers. The spread operation makes a shallow copy before sort mutates it.
Limits and mistakes
NaN does not have a useful numeric ordering through subtraction. Validate mixed inputs before sorting, and avoid converting empty strings to zero accidentally. For descending order use b minus a.
Check the result
Expect [-1,2,10,30], followed by the unchanged original array. Include negatives, equal numbers, and decimal values in your own checks.
Sources
Reference documentation for the behavior used in this guide: