- 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

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

Following is the code −

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);

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

- Related Questions & Answers
- Sorting numbers according to the digit root JavaScript
- Sorting Array based on another array JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Program to sort numbers based on 1 count in their binary representation in Python
- Maximum and minimum sums from two numbers with digit replacements in C++
- Sorting string of words based on the number present in each word using JavaScript
- Sorting the numbers from within in JavaScript
- Digit distance of two numbers - JavaScript
- Sorting according to weights of numbers in JavaScript
- Program to sort out phrases based on their appearances in Python
- How do I change a tag's inner HTML based on their order in JavaScript?
- How to get all the services based on their status in PowerShell?
- How to select data frame columns based on their class in R?
- How to select data.table object columns based on their class in R?
- Finding the nth digit of natural numbers JavaScript

Advertisements