0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Sort Array in Ascending Order

Use the JavaScript sort() method with a compare function like array.sort((a, b) => a - b) to sort an array in ascending order.
📋

Examples

Input[3, 1, 4, 2]
Output[1, 2, 3, 4]
Input[10, -5, 0, 7]
Output[-5, 0, 7, 10]
Input[]
Output[]
🧠

How to Think About It

To sort an array in ascending order, compare each pair of numbers and arrange them so smaller numbers come before larger ones. The 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

1
Get the input array.
2
Use the sort method with a compare function that subtracts the first element from the second.
3
The sort method rearranges the array based on the compare function results.
4
Return or print the sorted array.
💻

Code

javascript
const array = [3, 1, 4, 2];
array.sort((a, b) => a - b);
console.log(array);
Output
[1, 2, 3, 4]
🔍

Dry Run

Let's trace sorting the array [3, 1, 4, 2] through the code.

1

Initial array

[3, 1, 4, 2]

2

Compare 3 and 1

3 - 1 = 2 (positive), so 1 comes before 3

3

Compare 3 and 4

3 - 4 = -1 (negative), so 3 stays before 4

4

Compare 4 and 2

4 - 2 = 2 (positive), so 2 comes before 4

5

Final sorted array

[1, 2, 3, 4]

ComparisonResultAction
3 vs 12 (positive)Swap to put 1 before 3
3 vs 4-1 (negative)Keep order
4 vs 22 (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

Using a for loop and swapping
javascript
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);
This manual method uses nested loops to compare and swap elements but is less efficient and more code than using <code>sort()</code>.
Using spread operator and sort
javascript
const array = [3, 1, 4, 2];
const sortedArray = [...array].sort((a, b) => a - b);
console.log(sortedArray);
This creates a new sorted array without changing the original, useful when you want to keep the original array unchanged.

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²).

ApproachTimeSpaceBest For
Built-in sort() with compareO(n log n)O(1)General use, fast and simple
Manual nested loopsO(n²)O(1)Learning or very small arrays
Spread operator + sort()O(n log n)O(n)When original array must stay unchanged
💡
Always provide a compare function like (a, b) => a - b when sorting numbers to avoid incorrect order.
⚠️
Not using a compare function causes sort() to sort numbers as strings, leading to wrong order like [1, 10, 2].