Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sorting the numbers from within in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and reorders the digits of all the numbers internally in a specific order (let's say in ascending order for the sake of this problem).
For example: If the array is ?
const arr = [543, 65, 343, 75, 567, 878, 87];
Then the output should be ?
const output = [345, 56, 334, 57, 567, 788, 78];
Therefore, let's write the code for this function ?
Example
The code for this will be ?
const arr = [543, 65, 343, 75, 567, 878, 87];
const ascendNumber = num => {
const numArr = String(num).split('').map(el => +el);
numArr.sort((a, b) => a - b);
return numArr.join('');
};
const sortDigits = arr => {
const res = [];
for(let i = 0; i
Output
The output in the console will be ?
[
'345', '56',
'334', '57',
'567', '788',
'78'
]
How It Works
The solution uses two functions:
-
ascendNumber()- Converts a number to a string, splits into individual digits, sorts them in ascending order, and joins them back -
sortDigits()- Iterates through the array and applies the digit sorting to each number
Alternative Using map()
We can simplify the solution using the map() method:
const arr = [543, 65, 343, 75, 567, 878, 87];
const sortDigits = arr => {
return arr.map(num => {
return String(num)
.split('')
.sort()
.join('');
});
};
console.log(sortDigits(arr));
[ '345', '56', '334', '57', '567', '788', '78' ]
Conclusion
This approach efficiently sorts digits within each number by converting to strings, splitting into arrays, sorting, and rejoining. The map() method provides a cleaner, more functional programming approach.
Advertisements
