Sorting the numbers from within in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers and reorders the digit 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 < arr.length; i++){
      res.push(ascendNumber(arr[i]));
   };
   return res;
};
console.log(sortDigits(arr));

Output

The output in the console will be −

[
   '345', '56',
   '334', '57',
   '567', '788',
   '78'
]
raja
Published on 19-Oct-2020 10:40:33
Advertisements