Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting numbers based on their digit sums in JavaScript
We are required to write a JavaScript function that takes in an array of positive integers and sorts them based on their digit sums in descending order. Numbers with higher digit sums appear first.
Problem Statement
Given an array of positive integers, sort the array so that numbers with the highest digit sum come first, followed by numbers with lesser digit sums.
For example, if the input array is:
const arr = [5, 34, 1, 13, 76, 8, 78, 101, 57, 565];
The output should be:
[565, 78, 76, 57, 8, 34, 5, 13, 101, 1]
Understanding Digit Sums
The digit sum is calculated by adding all digits of a number:
- 565: 5 + 6 + 5 = 16 (highest)
- 78: 7 + 8 = 15
- 76: 7 + 6 = 13
- 1: 1 (lowest)
Solution Implementation
const arr = [5, 34, 1, 13, 76, 8, 78, 101, 57, 565];
const addDigits = (num, sum = 0) => {
if(num){
return addDigits(Math.floor(num / 10), sum + (num % 10));
};
return sum;
};
const sortByDigitSum = (arr = []) => {
arr.sort((a, b) => {
return addDigits(b) - addDigits(a);
});
return arr;
};
console.log("Original array:", arr);
sortByDigitSum(arr);
console.log("Sorted by digit sum:", arr);
Original array: [ 5, 34, 1, 13, 76, 8, 78, 101, 57, 565 ] Sorted by digit sum: [ 565, 78, 76, 57, 8, 34, 5, 13, 101, 1 ]
How the Algorithm Works
The solution uses two key functions:
- addDigits(): Recursively calculates the sum of all digits in a number
- sortByDigitSum(): Sorts the array using a custom comparator that compares digit sums
The recursive addDigits function extracts the last digit using modulo operator (num % 10) and removes it using integer division (Math.floor(num / 10)).
Alternative Non-Recursive Approach
const calculateDigitSum = (num) => {
let sum = 0;
while (num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
return sum;
};
const arr2 = [5, 34, 1, 13, 76, 8, 78, 101, 57, 565];
arr2.sort((a, b) => calculateDigitSum(b) - calculateDigitSum(a));
console.log("Sorted with iterative approach:", arr2);
Sorted with iterative approach: [ 565, 78, 76, 57, 8, 34, 5, 13, 101, 1 ]
Conclusion
Sorting by digit sum requires calculating the sum of digits for each number and using a custom comparator. Both recursive and iterative approaches work effectively for this problem.
