将数组中乱序的红黄蓝绿进行排序,达到[红...黄...蓝...绿...]的效果

要求:

数组:
["", "", "", "绿", "", "绿", "", "绿", "", "", ""]
排序成:
["", "", "", "", "", "", "", "", "绿", "绿", "绿"]

 

思路1:

将数组中的红黄蓝绿对应成数字1,2,3,4,使用sort进行从小达到排序,然后把数组中的数字对应回成红黄蓝绿

let arr=["", "", "", "绿", "", "绿", "", "绿", "", "", ""]
function a(){
    //map遍历 把文字替换成数字
    let newArr=arr.map(c=>{
        return c.replace('',1).replace('',2).replace('',3).replace('绿',4)
    })
    //排序数字
    newArr=newArr.sort((a,b)=>a-b)
    //把数字替换成文字
    newArr=newArr.map(c=>{
        return c.replace(1,'').replace(2,'').replace(3,'').replace(4,'绿')
    })
    console.log(newArr)//["红","红","红","黄","黄","蓝","蓝","蓝","绿","绿","绿"]
}
a()

 

思路2:

创建文字对应的数字对象,新数组是map出来的,元素有文字对应的数字,排序数字,map遍历出文字

function b(){
    //创建map对象
    let mapObj={
        '红':1,
        '黄':2,
        '蓝':3,
        '绿':4,
    }
    let mapArr=arr.map(c=>{
        return {
            text:c,//对应文字
            num:mapObj[c],//对应数字
        }
    })
    let newArr=mapArr.sort((a,b)=>a.num-b.num)//排序数字
    newArr=newArr.map(c=>{
        return c.text//map出文字
    })
    console.log(newArr)
}
b()

 

posted @ 2020-09-19 11:49  herry菌  阅读(495)  评论(0编辑  收藏  举报