碰个字符串数字,按照每个数字的每个位数相加的比重排序,最后输出字符串数字按照重数比重升序,排序

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、遍历排序后的数组对象,取出原字符串拼接,即是按照重数排序;

 



  

posted @ 2020-01-15 09:42  黎明之光123  阅读(255)  评论(0编辑  收藏  举报