zoukankan      html  css  js  c++  java
  • 数组多重排序

    写法1

    //直接在sort函数中自定义书写,适用性强
    array.sort(function(ob1,ob2) {
        if (ob1.strength > ob2.strength) {
            return 1;
        } else if (ob1.strength < ob2.strength) { 
            return -1;
        }
        // 当strength相等的时候会以name来进行比较
        if (ob1.name < ob2.name) { 
            return -1;
        } else if (ob1.name > ob2.name) {
            return 1
        } else { // nothing to split them
            return 0;
        }
    })

    写法2

    //比较使用一个通用函数,未必适用所有情况,字符串可以使用>比较,比较的是其字典序
    cmp = function(a, b) {
        if (a > b) return +1;
        if (a < b) return -1;
        return 0;
    }
    //直接使用原生的sort函数,当前面的比较为0时候,使用后面的比较
    array.sort(function(a, b) { 
        return cmp(a.strength,b.strength) || cmp(a.name,b.name)
    })

    写法3

    //localeCompare比较会使用当地的字母比较规则,区别与>的unicode字典序
    objects.sort(function (a, b) {
        return a.strength - b.strength || a.name.localeCompare(b.name);
    });

    写法4

    使用thenBy.js

    出处: https://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second

  • 相关阅读:
    一点优化小知识
    网站结构优化之一
    [JOISC 2016 Day 3] 电报
    [HDU 6157] The Karting
    [JOISC 2015 Day2] Keys
    Educational Codeforces Round 107 (Rated for Div. 2)
    [JOISC 2020 Day4] 治疗计划
    CF1131G Most Dangerous Shark
    [APIO2016] 划艇
    [ICPC World Finals 2018] 绿宝石之岛
  • 原文地址:https://www.cnblogs.com/mengff/p/7898160.html
Copyright © 2011-2022 走看看