let str = '520 121 123 101 158 100 954';
function sortNum(str) {
let arr = str.split(' ');
let finalList = [];
let result = '';
let jumpList = [];
arr.forEach((item)=>{
let startNum = 0;
item.split('').forEach((cur)=>{
startNum+= Number(cur);
});
jumpList.push(startNum);
});
arr.forEach((item,index)=>{
finalList.push({
a:item,
b:jumpList[index]
});
});
finalList.sort((a,b)=> a.b - b.b);
console.log(finalList);
finalList.forEach((item)=>{
result+=(item.a+' ');
});
console.log(result);
思路:
1、字符转数组;
2、小颗粒字符串数字相加,组成比重数组;
3、把原字符串数组和比重数组,放在新的数组中,对数组对象的比重排序,从而排序数组对象;
4、遍历排序后的数组对象,取出原字符串拼接,即是按照重数排序;