zoukankan      html  css  js  c++  java
  • JS—如何按日期对象数组进行排序,然后按时间顺序进行降序排序?

    排序在项目中还是比较常见的。特别后台·管理系统,动不动就有升序降序的排序操作

    1. 有以下数组
    // 如何对数组进行排序,从最早到最新,反之亦然?
    
    const arr = [
      {id: 1, value : "value1", date: "2018-08-08", time: "15:27:17"},
      {id: 2, value : "value2", date: "2018-08-09", time: "12:27:17"},
      {id: 3, value : "value3", date: "2018-08-10", time: "17:27:17"},
      {id: 4, value : "value4", date: "2018-08-10", time: "01:27:17"},
      {id: 5, value : "value5", date: "2018-08-10", time: "09:27:17"},
      {id: 6, value : "value6", date: "2018-08-10", time: "23:27:17"},
      {id: 7, value : "value7", date: "2018-08-10", time: "16:27:17"},
      {id: 8, value : "value8", date: "2018-08-11", time: "10:27:17"}
    ];
    
    arr.sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time));
    console.log(arr);

    这是在控制台上输出的结果:

    2. 若要排序为降序,只需切换as和bs:
    const arr = [
    {id: 1, value : "value1", date: "2018-08-08", time: "15:27:17"},
    {id: 2, value : "value2", date: "2018-08-09", time: "12:27:17"},
    {id: 3, value : "value3", date: "2018-08-10", time: "17:27:17"},
    {id: 4, value : "value4", date: "2018-08-10", time: "01:27:17"},
    {id: 5, value : "value5", date: "2018-08-10", time: "09:27:17"},
    {id: 6, value : "value6", date: "2018-08-10", time: "23:27:17"},
    {id: 7, value : "value7", date: "2018-08-10", time: "16:27:17"},
    {id: 8, value : "value8", date: "2018-08-11", time: "10:27:17"}
    ];
    
    arr.sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
    console.log(arr);

    这是在控制台上输出的结果,如果图片无法显示,复制代码到控制台输出即可观察到变化

  • 相关阅读:
    快速理解平衡二叉树、B-tree、B+tree、B*tree
    centos 7(6) linux系统安装 mysql5.7.17(glibc版)
    关于使用Hibernate+spring+dubbo的实现微服务对象查询
    Keepalived+Nginx实现高可用(HA)
    Nginx源码安装
    Keepalived安装与配置
    单点fastDfs+centos7搭建
    Dubbo+zookeeper使用方法以及注意事项
    mac 下 iterm2 不能使用 rz sz
    java 无符号整型
  • 原文地址:https://www.cnblogs.com/Ky-Thompson23/p/13390824.html
Copyright © 2011-2022 走看看