JavaScript Program to Sort Array in Ascending Order
sort() method with a compare function like array.sort((a, b) => a - b) to sort an array in ascending order.Examples
How to Think About It
sort() method can take a function that tells it how to compare two numbers by subtracting one from the other. If the result is negative, the first number goes before the second; if positive, it goes after.Algorithm
Code
const array = [3, 1, 4, 2]; array.sort((a, b) => a - b); console.log(array);
Dry Run
Let's trace sorting the array [3, 1, 4, 2] through the code.
Initial array
[3, 1, 4, 2]
Compare 3 and 1
3 - 1 = 2 (positive), so 1 comes before 3
Compare 3 and 4
3 - 4 = -1 (negative), so 3 stays before 4
Compare 4 and 2
4 - 2 = 2 (positive), so 2 comes before 4
Final sorted array
[1, 2, 3, 4]
| Comparison | Result | Action |
|---|---|---|
| 3 vs 1 | 2 (positive) | Swap to put 1 before 3 |
| 3 vs 4 | -1 (negative) | Keep order |
| 4 vs 2 | 2 (positive) | Swap to put 2 before 4 |
Why This Works
Step 1: Using sort() method
The sort() method changes the array order by comparing elements.
Step 2: Compare function logic
The compare function (a, b) => a - b returns a negative number if a is less than b, which means a should come first.
Step 3: Resulting order
This causes the array to be sorted from smallest to largest number.
Alternative Approaches
const array = [3, 1, 4, 2]; for(let i = 0; i < array.length; i++) { for(let j = i + 1; j < array.length; j++) { if(array[i] > array[j]) { const temp = array[i]; array[i] = array[j]; array[j] = temp; } } } console.log(array);
const array = [3, 1, 4, 2]; const sortedArray = [...array].sort((a, b) => a - b); console.log(sortedArray);
Complexity: O(n log n) time, O(1) space
Time Complexity
The built-in sort() method typically uses an efficient sorting algorithm like Timsort or QuickSort, which runs in O(n log n) time for n elements.
Space Complexity
Sorting is done in place, so extra space is minimal, O(1), except for some internal stack space depending on the algorithm.
Which Approach is Fastest?
Using the built-in sort() with a compare function is fastest and simplest compared to manual loops which are O(n²).
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in sort() with compare | O(n log n) | O(1) | General use, fast and simple |
| Manual nested loops | O(n²) | O(1) | Learning or very small arrays |
| Spread operator + sort() | O(n log n) | O(n) | When original array must stay unchanged |
(a, b) => a - b when sorting numbers to avoid incorrect order.sort() to sort numbers as strings, leading to wrong order like [1, 10, 2].