- 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 according to weights of numbers in JavaScript

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 ]

- Related Questions & Answers
- Sorting numbers according to the digit root JavaScript
- Sorting objects according to days name JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting according to number of 1s in binary representation using JavaScript
- Sorting an array that contains the value of some weights 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
- Sorting the numbers from within in JavaScript
- Algorithm for sorting array of numbers into sets in JavaScript
- Sorting numbers based on their digit sums in JavaScript
- Sort the numbers according to their sum of digits in C++
- Sorting an array according to another array using pair in STL in C++
- Uneven sorting of array in JavaScript
- Assign weights to edges such that longest path in terms of weights is minimized in C++

Advertisements