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
Sorting digits of all the number of array - 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];
Approach
The solution involves converting each number to a string, splitting it into individual digits, sorting those digits in ascending order, and then joining them back into a number.
Example
Following is the code ?
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 < arr.length; i++){
res.push(ascendNumber(arr[i]));
};
return res;
};
console.log(sortDigits(arr));
[
'345', '56',
'334', '57',
'567', '788',
'78'
]
How It Works
The ascendNumber function processes each individual number:
-
String(num).split('')converts the number to an array of digit characters -
map(el => +el)converts each character back to a number for proper sorting -
sort((a, b) => a - b)sorts digits in ascending order -
join('')combines the sorted digits back into a string
Alternative Implementation
Here's a more concise version using map() instead of a for loop:
const arr = [543, 65, 343, 75, 567, 878, 87];
const sortDigitsInArray = arr => {
return arr.map(num => {
return String(num)
.split('')
.sort((a, b) => a - b)
.join('');
});
};
console.log(sortDigitsInArray(arr));
[
'345', '56',
'334', '57',
'567', '788',
'78'
]
Conclusion
This approach efficiently sorts the digits within each number by converting to strings, sorting individual characters numerically, and reconstructing the result. The map() method provides a cleaner functional programming approach.
