

- 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
Sorting numbers according to the digit root JavaScript
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 ]
- Related Questions & Answers
- Sorting according to weights of numbers in JavaScript
- Sorting numbers based on their digit sums in JavaScript
- Sorting objects according to days name JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting the numbers from within in JavaScript
- Sorting according to number of 1s in binary representation using JavaScript
- Sorting a HashMap according to keys in C#
- Sorting a HashMap according to keys in Java
- Sorting a HashMap according to values in Java
- Finding the nth digit of natural numbers JavaScript
- Digit distance of two numbers - JavaScript
- Sum Root to Leaf Numbers in Python
- Finding nth digit of natural numbers sequence in JavaScript
- Finding sequential digit numbers within a range in JavaScript
- Sort the numbers according to their sum of digits in C++
Advertisements