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

    1.纯数字数组

    // 纯数字数组排序
    let arr = [3, 4, 5, 1, 2]
                // 从小到大
                console.log(arr.sort());
                // 也是从小到大
                console.log(arr.sort((a, b) => a - b));
                // 从大到小
                console.log(arr.sort((a, b) => b - a));

    2.数组对象属性排序

    (1)对象的属性值是数字

    例如,下面是根据age排序

    let arr = [
                { name: 'zs', age: 12 },
                { name: 'ls', age: 6 },
                { name: 'ww', age: 24 },
            ];
            // 对象的数字属性排序
            // 从小到大
            let compare = (property) => (a, b) => a[property] - b[property]
            console.log(arr.sort(compare('age')));
            // 从大到小
            let compare2 = (property) => (a, b) => b[property] - a[property]
            console.log(arr.sort(compare2('age')));

    (2)对象的属性值不是数字

    ①按英文字母a-z排序 或 z-a

     let data = [
                    { name: 'Bob', score: '95', age: '18' },
                    { name: 'Amy', score: '86', age: '18' },
                    { name: 'Coco', score: '36', age: '18' },
                    { name: 'Mark', score: '80', age: '18' },
                    { name: 'Frank', score: '40', age: '18' }
                ];
              let newData = [...data]
              let newData2 = [...data]
            // a-z
            let compare =  property=>(a,b)=> a[property].charCodeAt(0)- b[property].charCodeAt(0)
            console.log(newData.sort(compare('name')));
    
            // z- a
            let compare2= property=>(a,b)=> b[property].charCodeAt(0)- a[property].charCodeAt(0)
            console.log(newData2.sort(compare2('name')));

    ②按拼音顺序排序 或 按拼音逆序排序

      let data = [
                  {name: '张三',age:12},
                  {name: '李四',age:23},
                  {name: '王五',age:23},
                  {name: '陈六',age:23},
              ]
    
              let newData = [...data]
              let newData2 = [...data]
            // 拼音a-z
              let compare = property=>(a,b)=> a[property].localeCompare(b[property],'zh')
           // 拼音z-a
           let compare2 = property=>(a,b)=> b[property].localeCompare(a[property],'zh')  
           console.log(newData.sort(compare('name')));
           console.log(newData2.sort(compare2('name')));
  • 相关阅读:
    PostgreSQL pg_ident.conf 文件简析
    使用 iptables 限制黑客猜密码续—深入 recent 模块
    从零开始安装 Drupal 7
    使用tween.js移动three.js相机创建转场动画
    容器化导致RocketMQ消息囤积的原因和解决方案
    linux序章(第一集)
    使用DockerFile 构建nginx镜像
    git的常用指令
    使用docker起一个mysql服务
    Windows 8自动登录
  • 原文地址:https://www.cnblogs.com/luguankun/p/14408131.html
Copyright © 2011-2022 走看看