Sorting numbers according to the digit root JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Digit Root

The digit root of a positive integer is defined as the sum of all of its digits.

We are required to write a JavaScript function that takes in an array of integers. The function should sort it in such a way that if a comes before b then the digit root of a is less than or equal to the digit root of b. If two numbers have the same digit root, the smaller one (in the regular sense) should come first.

For example, 4 and 13 have the same digit root, however 4 < 13 thus 4 comes before 13 in any digitRoot sorting where both are present.

For example −

If the input array is −

const arr = [13, 20, 7, 4];

Then the output should be −

const output = [20, 4, 13, 7];

Example

const arr = [13, 20, 7, 4];
const digitSum = (num, sum = 0) => {
   if(num){
      return digitSum(Math.floor(num / 10), sum + (num % 10));
   };
   return sum;
};
const digitalSort = (arr = []) => {
   const sorter = (a, b) => {
      return (digitSum(a) - digitSum(b)) || (a - b);
   };
   arr.sort(sorter);
};
digitalSort(arr);
console.log(arr);

Output

This will produce the following output −

[ 20, 4, 13, 7 ]
raja
Published on 25-Nov-2020 05:33:39
Advertisements