在 JavaScript 中根据数字总和对数字进行排序

javascriptweb developmentfront end technology

问题

我们需要编写一个 JavaScript 函数,该函数将一个正整数数组 arr 作为第一个也是唯一的参数。

我们的函数应该对输入数组进行排序,使数字总和最高的数字排在最前面,然后是数字总和较小的数字。

例如,如果函数的输入是 −

输入

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

输出

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

输出说明

因为 565 的数字和最高为 16,其次是 78 和 76,而 101 和 1 的数字和最低,分别为 2 和 1

示例

以下是代码 −

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 ]

相关文章