How to sort an array of integers in JavaScript ?

To sort an array of integers in JavaScript, use the sort() method with a custom comparison function to ensure numerical (not lexicographical) sorting. Here’s a detailed guide with examples:

1. Basic Numerical Sorting

By default, sort() treats elements as strings, which can lead to incorrect results for numbers.
Solution: Pass a comparison function to sort().

Ascending Order (Small → Large)

const numbers = [40, 1, 5, 200];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 40, 200]

Descending Order (Large → Small)

const numbers = [40, 1, 5, 200];
numbers.sort((a, b) => b - a);
console.log(numbers); // [200, 40, 5, 1]

2. Why the Comparison Function Matters

Without a comparison function, sort() converts numbers to strings and sorts them lexicographically (alphabetically):

const numbers = [10, 2, 1, 5];
numbers.sort();
console.log(numbers); // [1, 10, 2, 5] (incorrect for numbers!)

3. Copying the Array Before Sorting

The sort() method mutates the original array. To avoid this, create a copy first:

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]

4. Sorting Subranges

Use slice() to sort a subset of the array:

const numbers = [9, 3, 2, 8, 7];
// Sort elements from index 1 to 3
numbers.slice(1, 4).sort((a, b) => a - b);
console.log(numbers); // [9, 2, 3, 8, 7]

5. Handling Edge Cases

Negative Numbers

The comparison function works naturally with negatives:

const numbers = [-5, 10, -1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [-5, -1, 3, 10]

Large Arrays

Modern JavaScript engines (like V8) use efficient sorting algorithms, so performance is rarely an issue for typical use cases.

Key Takeaways

  • Always use (a, b) => a - b for ascending order or (a, b) => b - a for descending order.
  • The sort() method modifies the original array. Use [...array].sort() to preserve the original.
  • Lexicographical sorting (default) is not suitable for numbers.

Summary Code

// Ascending order
const sortedAsc = [10, 2, 1, 5].sort((a, b) => a - b);

// Descending order
const sortedDesc = [10, 2, 1, 5].sort((a, b) => b - a);

// Immutable sort
const original = [3, 1, 4];
const sortedCopy = [...original].sort((a, b) => a - b);

Leave a Reply

Your email address will not be published. Required fields are marked *