在 JavaScript 中对数字进行排序

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 23:40:17

我们需要编写一个 JavaScript 函数,该函数接收一个数字数组,并按照特定顺序(为了解决这个问题,我们假设按升序排列)重新排列所有数字的数字。

例如:如果数组是 −

const arr = [543, 65, 343, 75, 567, 878, 87];

那么输出应该是 −

const output = [345, 56, 334, 57, 567, 788, 78];

因此,让我们编写该函数的代码 −

示例

其代码为 −

const arr = [543, 65, 343, 75, 567, 878, 87];
const ascendNumber = num => {
   const numArr = String(num).split('').map(el => +el);
   numArr.sort((a, b) => a - b);
   return numArr.join('');
};
const sortDigits = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      res.push(ascendNumber(arr[i]));
   };
   return res;
};
console.log(sortDigits(arr));

输出

控制台中的输出将是 −

[
   '345', '56',
   '334', '57',
   '567', '788',
   '78'
]

相关文章


有用资源