zoukankan      html  css  js  c++  java
  • js 数组中的值排序

    //对数组中的多个对象对某一个字段按照字母先后顺序排序
    
    var array = [
            {"id":"111","user":"D"},
            {"id":"222","user":"B"},
            {"id":"111","user":"A"},
            {"id":"333","user":"C"},
            {"id":"444","user":"F"},
            {"id":"555","user":"E"}
        ];
    
    //对数组中的user字段进行排序
    
        arr.sort(function(a,b){
                return a.user.localeCompare(b.user)
            });
    
    
    //排序后的结果
        var array = [
            {"id":"111","user":"A"},
            {"id":"222","user":"B"},
            {"id":"333","user":"C"},
            {"id":"111","user":"D"},
            {"id":"555","user":"E"},
            {"id":"444","user":"F"}
            ];
    //按id的数字大小升序或者是降序排序
    
          function compare(property,desc) {
                return function (a, b) {
                    var value1 = a[property];
                    var value2 = b[property];
                    if(desc==true){
                        // 升序排列
                        return value1 - value2;
                    }else{
                        // 降序排列
                        return value2 - value1;
                    }
                }
            }
    
            arr.sort(compare("id",true));    //id 为数组中需要排序的字段,true为升序,false为降序排列
  • 相关阅读:
    Java异常面试题
    Quickhit快速击键
    多态and接口
    Java面向对象编程概述
    学生管理系统--分层开发
    类型转换
    文件上传
    ongl(示例3-6 多值类型的数据处理)
    ongl(原始类型和包装类型)
    Interceptor
  • 原文地址:https://www.cnblogs.com/yydxh/p/13748766.html
Copyright © 2011-2022 走看看