- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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);

The output in the console will be −

[ 23, 8, 26, 54, 89 ]

- Related Questions & Answers
- Digital Root (repeated digital sum) of the given large integer in C++ Program
- Which algorithm does the JavaScript Array#sort() function use?
- Tim Sort Algorithm in C++
- Find Nth positive number whose digital root is X in C++
- Print a number containing K digits with digital root D in C++
- C++ Program to find Numbers in a Range with Given Digital Root
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
- Difference Between Digital Signature and Digital Certificate
- What is digital certificate and digital signature?
- A sorting algorithm that slightly improves on selection sort?
- Fuzzy Search Algorithm in JavaScript
- JavaScript: Adjacent Elements Product Algorithm
- C++ Program to Implement Merge Sort Algorithm on Linked List
- Digital Subscriber Lines
- Digital Integrated Circuits

Advertisements