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]Sorting numbers in JavaScript is like being given a box with numbers that get sorted alphabetically instead of numerically! 📦❌
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 comparisonYou 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!Function receives two elements and should return:
// 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
}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// ❌ 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]// ❌ 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);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 💪