Sorting numbers based on their digit sums in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of positive integers, arr, as the first and the only argument.

Our function should sort the input array in such a way that the number that have the highest digit sum comes first followed by the numbers with lesser digit sums.

For example, if the input to the function is −

Input

const arr = [5, 34, 1, 13, 76, 8, 78, 101, 57, 565];

Output

const output = [565, 78, 76, 57, 8, 34, 5, 13, 101, 1];

Output Explanation

Because 565 have the highest digit sum of 16, followed by 78 and 76 and 101 and 1 have the least digit sum of 2 and 1 respectively

Example

Following is the code −

 Live Demo

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;
};
sortByDigitSum(arr);
console.log(arr);

Output

[ 565, 78, 76, 57, 8, 34, 5, 13, 101, 1 ]

Updated on: 22-Apr-2021

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements