- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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 −
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 ]
Advertisements