How to sort an array of numbers correctly?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Arrays #JS Basics

Brief Answer

To correctly sort an array of numbers in JavaScript, you need to use [sort()] with a comparison function. Without a function, numbers are sorted as strings, which leads to incorrect results! 🔢

const numbers = [10, 2, 30, 4];
 
// ❌ Wrong — sorts as strings
console.log(numbers.sort()); // [10, 2, 30, 4] — wrong!
 
// ✅ Correct — with comparison function
console.log(numbers.sort((a, b) => a - b)); // [2, 4, 10, 30]

Full Answer

Sorting numbers in JavaScript is like being given a box with numbers that get sorted alphabetically instead of numerically! 📦❌

Problem with sort() without function

The [sort()] method by default sorts elements as strings:

const numbers = [10, 2, 30, 4, 100];
 
// Sorting without function
console.log(numbers.sort()); 
// [10, 100, 2, 30, 4] — wrong!
// Because '10' < '2' in string comparison

Correct Number Sorting

You need to pass a comparison function to [sort()]:

const numbers = [10, 2, 30, 4, 100];
 
// Ascending (smaller to larger)
console.log(numbers.sort((a, b) => a - b)); 
// [2, 4, 10, 30, 100] — correct!
 
// Descending (larger to smaller)
console.log(numbers.sort((a, b) => b - a)); 
// [100, 30, 10, 4, 2] — correct!

How Comparison Function Works

Function receives two elements and should return:

  • Negative number — first element should come first
  • Positive number — second element should come first
  • Zero — elements are equal
// Simple function for numbers
(a, b) => a - b
 
// Same as:
function compare(a, b) {
  if (a < b) return -1; // a first
  if (a > b) return 1;  // b first
  return 0;             // equal
}

Sorting While Preserving Original

The [sort()] method modifies the original array:

const numbers = [3, 1, 4, 1, 5];
 
// ❌ Modifies original
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 1, 3, 4, 5] — original changed!
 
// ✅ Preserve original
const original = [3, 1, 4, 1, 5];
const sorted = [...original].sort((a, b) => a - b);
console.log(original); // [3, 1, 4, 1, 5] — unchanged
console.log(sorted);   // [1, 1, 3, 4, 5] — new copy

Common Mistakes

Sorting without function

// ❌ Wrong
const nums = [10, 2, 30];
console.log(nums.sort()); // [10, 2, 30] — wrong!
 
// ✅ Correct
console.log(nums.sort((a, b) => a - b)); // [2, 10, 30]

Forgetting sort() modifies array

// ❌ Mistake — lose original order
const scores = [85, 92, 78];
const sorted = scores.sort((a, b) => a - b); 
// scores and sorted are the same array!
 
// ✅ Correct — make copy first
const scores2 = [85, 92, 78];
const sorted2 = [...scores2].sort((a, b) => a - b);

Simple Rules

  1. sort() without function — sorts as strings, not suitable for numbers ⚠️
  2. sort((a, b) => a - b) — ascending for numbers 🔼
  3. sort((a, b) => b - a) — descending for numbers 🔽
  4. sort() modifies — original changes! 🔄
  5. Copy before sort() — if you need original 🆕

Proper number sorting helps avoid strange errors in programs! 💡


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪