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


    要求:

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

    思路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()
  • 相关阅读:
    setState 是异步吗?
    React优化点滴
    JS原型,作用域,this,闭包
    Webpack 模块化打包优化
    JS异步编程
    Web网络安全
    Http2.0和Http3.0
    Http协议基础
    Harris算子以及未来的规划...
    剑指offer 二维数组查找
  • 原文地址:https://www.cnblogs.com/wuhairui/p/13695594.html
Copyright © 2020-2023  润新知