Digital root sort algorithm JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Digit root of some positive integer is defined as the sum of all of its digits. We are given an array of integers. We have to sort it in such a way that if a comes before b if 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,

for a = [13, 20, 7, 4],
the output should be [20, 4, 13, 7].

Let’s write the code for this problem −

We will divide it in two functions, a recursive function that counts the sum of digits of a number, and then a sorting function that orders the element on the basis of the sum of digits.

The code for this will be −

Example

const arr = [54, 23, 8, 89, 26];
const recursiveCount = (num, count = 0) => {
   if(num){
      return recursiveCount(Math.floor(num/10), count+num%10);
   };
   return count;
};
const sorter = (a, b) => {
   const countDifference = recursiveCount(a) - recursiveCount(b);
   return countDifference || a - b;
};
arr.sort(sorter);
console.log(arr);

Output

The output in the console will be −

[ 23, 8, 26, 54, 89 ]
raja
Published on 21-Aug-2020 13:13:45
Advertisements