Sorting is one of the most common operations in programming. In this article, we’ll learn how to sort an array of integers in ascending order using JavaScript.
We will also explore a simple custom sorting logic using loops and array manipulation.
🧠 Problem Statement
Given a number (or array of numbers), we want to sort all digits in ascending order.
For example:
- Input:
123496758789456 - Output:
123445567778899
💡 Approach
We will:
- Convert the number into a string
- Split it into individual digits
- Compare and rearrange digits using loops
- Return the sorted result
This approach demonstrates basic sorting logic without using built-in sort().
💻 JavaScript Program
const nos = 123496758789456;
console.log("Original:", nos);
const sorted = sorter(nos).join('');
console.log("Sorted:", sorted);
function sorter(nos) {
const splitted = nos.toString().split('');
for (let i = 0; i < splitted.length; i++) {
for (let j = i + 1; j < splitted.length; j++) {
if (parseInt(splitted[j - 1]) > parseInt(splitted[j])) {
let temp = splitted[j - 1];
splitted.splice(j - 1, 1);
splitted.splice(j, 0, temp);
}
}
}
return splitted;
}
🔍 How It Works
Step 1: Convert Number to String
nos.toString().split('')
This converts the number into an array of digits.
Step 2: Compare Adjacent Elements
We use nested loops to compare each digit with the next ones.
Step 3: Swap Elements
If the previous digit is greater than the next one, we swap them using splice().
📊 Output Example
Input:
123496758789456
Output:
123445567778899
⚡ Better Approach (Recommended)
Instead of manual sorting, JavaScript provides a built-in method:
const nos = 123496758789456;
const sorted = nos
.toString()
.split('')
.sort((a, b) => a - b)
.join('');
console.log(sorted);
🚀 Key Takeaways
- Sorting can be done using loops or built-in methods
- Manual sorting helps understand algorithm logic
.sort()is the most efficient and readable approach in JavaScript- Always prefer built-in functions in real-world applications
🎯 Conclusion
Sorting digits is a great exercise to understand array manipulation and comparison logic in JavaScript. While manual sorting builds algorithmic thinking, built-in methods like .sort() make code cleaner and more efficient.
Keep practicing to strengthen your JavaScript fundamentals!
