根据JavaScript中数字的权重排序

数字的权重是该数字的位数的总和。例如-

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

我们需要编写一个包含数字数组的JavaScript函数。函数应按权重的升序对数字进行排序,如果两个数字恰好具有相同的权重,则应按实际的升序进行排列。

例如-

50和23具有相同的权重,因此应在50之前放置23,以保持实际的升序(仅在权重相等的情况下)

示例

为此的代码将是-

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

输出结果

控制台中的输出将是-

[
   1, 100, 2, 200, 3,
   46, 56, 66, 78, 99
]
猜你喜欢