对数组中所有数字进行排序 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/8 18:20: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' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

