zoukankan      html  css  js  c++  java
  • JavaScript对象数组根据某属性sort升降序排序

    1、自定义一个比较器,其参数为待排序的属性。

    2、将带参数的比较器传入sort()。

    var data = [
        {name: "Bruce", age: 23, id: 16, score: 80},
        {name: "Alice", age: 24, id: 12, score: 90},
        {name: "David", age: 21, id: 11, score: 70},
        {name: "Cindy", age: 22, id: 10, score: 100},
    ];


    data.sort(compareUp("age"));
    data.sort(compareDown("age"));


    function compareUp(propertyName) { // 升序排序
            if ((typeof data[0][propertyName]) != "number") { // 属性值为非数字
                  return function(object1, object2) {
                      var value1 = object1[propertyName];
                      var value2 = object2[propertyName];
                     return value1.localeCompare(value2);
                 }
           } else {
                return function(object1, object2) { // 属性值为数字
                      var value1 = object1[propertyName];
                      var value2 = object2[propertyName];
                     return value1 - value2;
                 }
           }
    }


    function compareDown(propertyName) { // 降序排序
           if ((typeof data[0][propertyName]) != "number") { // 属性值为非数字
               return function(object1, object2) {
                    var value1 = object1[propertyName];
                    var value2 = object2[propertyName];
                    return value2.localeCompare(value1);
               }
       } else {
            return function(object1, object2) { // 属性值为数字
                  var value1 = object1[propertyName];
                  var value2 = object2[propertyName];
                  return value2 - value1;
            }
        }
    }

  • 相关阅读:
    Meteor + node-imap(nodejs) + mailparser(nodejs) 实现完整收发邮件
    详解log4j2(上)
    循序渐进之Spring AOP(6)
    循序渐进之Spring AOP(5)
    循序渐进之Spring AOP(3)
    循序渐进之Spring AOP(4)
    循序渐进之Spring AOP(2)
    循序渐进之Spring AOP(1)
    通俗的解释JAVA wait/notify机制
    开发高性能JAVA应用程序基础(内存篇)
  • 原文地址:https://www.cnblogs.com/ranyonsue/p/9687868.html
Copyright © 2011-2022 走看看