js 数组根据特定规则排序

这篇博客介绍了如何使用JavaScript根据预设的字母顺序对数组对象进行排序。示例中展示了如何根据'name'属性的值重新排列对象数组,并提供了一个降序排序函数的封装示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 这里是根据指定的字母顺序来重新排序的

var objs = [
    {'name': 'A', 'type': 'fly'},
    {'name': 'B', 'type': 'blur'},
    {'name': 'C', 'type': 'wipe'},
    {'name': 'D', 'type': 'cube'},
    {'name': 'E', 'type': 'iris'},
    {'name': 'F', 'type': 'fade'}
];

objs.sort(function(a,b){
    // order是规则  objs是需要排序的数组
    var order = ["wipe", "fly", "iris", "flip", "cube",
        "blur", "zoom", "fade", "glow", "rotate"];
    return order.indexOf(a.type) - order.indexOf(b.type);
});

// 根据规则排序后新的数组
var result = objs.map(function(a){
    return a['name'];
});
--------------------- 
作者:know_yourself 
来源:CSDN 
原文:https://blog.csdn.net/qq_35010942/article/details/82467575 
版权声明:本文为博主原创文章,转载请附上博文链接!

//降序函数  封装
function Desc(arr, StrKey) {
    var desc = function(x, y) {
        return (x[StrKey] < y[StrKey]) ? 1 : -1
    };
    return arr.sort(desc)
}

 

 var aTemp = Desc(tmpMax, 'showRate'); 

        //积分排序   排名规则:优先大分,打分相同按照小分,小分相同按照累进分,累进分相同按照交手记录,如无交手记录则按照净胜分
function sortScores(a, b) {
            if (a["Score"] === b["Score"]) {
                if (a["Value1"] === b["Value1"]) {
                    if (a["Value2"] === b["Value2"]) {
                        return +a["Value3"] > +b["Value3"] ? 1 : +a["Value3"] < +b["Value3"] ? -1 : 0;
                    } else {
                        return +a["Value2"] < +b["Value2"] ? 1 : -1;
                    }
                } else {
                    return +a["Value1"] < +b["Value1"] ? 1 : -1;
                }
            } else {
                return +a["Score"] < +b["Score"] ? 1 : -1;

            }
        };


  data.sort(sortScores);
//以上排序是根据从大到小排序的,要是需要从小到大,则改成

function sortScores(a, b) {
            if (a["Score"] === b["Score"]) {
                if (a["Value1"] === b["Value1"]) {
                    if (a["Value2"] === b["Value2"]) {
                        return +a["Value3"] > +b["Value3"] ? 1 : +a["Value3"] < +b["Value3"] ? -1 : 0;
                    } else {
                        return +a["Value2"] > +b["Value2"] ? 1 : -1;
                    }
                } else {
                    return +a["Value1"] > +b["Value1"] ? 1 : -1;
                }
            } else {
                return +a["Score"] > +b["Score"] ? 1 : -1;

            }
        };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值