Sorting according to weights of numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The weight of a number is the sum of the digits of that number. For example −

The weight of 100 is 1
The weight of 22 is 4
The weight of 99 is 18
The weight of 123 is 6

We are required to write a JavaScript function that takes in an array of numbers. The function should sort the numbers in the increasing order of their weights, and if two numbers happens to have the same weight, they should be placed in actual increasing order.

For instance −

50 and 23 have the same weight, so 23 should be placed before 50 in order to maintain the actual increasing order (only in case of equal weights)

Example

The code for this will be −

const arr = [2, 1, 100, 56, 78, 3, 66, 99, 200, 46];
const calculateWeight = (num, sum = 0) => {
   if(num){
      return calculateWeight(Math.floor(num / 10), sum + (num % 10));
   };
   return sum;
};
const sorter = (a, b) => {
   return calculateWeight(a) − calculateWeight(b) || a − b;
}
arr.sort(sorter);
console.log(arr);

Output

And the output in the console will be −

[
   1, 100, 2, 200, 3,
   46, 56, 66, 78, 99
]
raja
Published on 25-Nov-2020 11:43:42
Advertisements