如何按两个字段对数组排序(包括日期)

时间:2018-06-19 12:35:28

标签: javascript sorting

我有一个对象数组,我想首先按日期排序,然后按其数值排序。

let arr = [  
  {date: 2018-06-19 12:05:43.232Z, value: 3},
  {date: 2018-06-20 12:05:43.232Z, value: 4},  
  {date: 2018-06-18 12:05:43.232Z, value: 2},  
  {date: 2018-06-20 12:05:43.232Z, value: 4}, 
  {date: 2018-06-19 12:05:43.232Z, value: 5},     
  {date: 2018-06-18 12:05:43.232Z, value: 5},  
  {date: 2018-06-20 12:05:43.232Z, value: 5},  
  {date: 2018-06-19 12:05:43.232Z, value: 4},  
]

我想按日期和值对每个索引进行排序,这样结果将是:

let arr = [
  {date: 2018-06-18 12:05:43.232Z, value: 2},
  {date: 2018-06-18 12:05:43.232Z, value: 5},

  {date: 2018-06-19 12:05:43.232Z, value: 3},
  {date: 2018-06-19 12:05:43.232Z, value: 4},
  {date: 2018-06-19 12:05:43.232Z, value: 5}, 

  {date: 2018-06-20 12:05:43.232Z, value: 3},
  {date: 2018-06-20 12:05:43.232Z, value: 4},     
  {date: 2018-06-20 12:05:43.232Z, value: 5},     
]

怎么办?

2 个答案:

答案 0 :(得分:5)

您可以将Array.sort与||一起使用

const res = arr.sort((a, b) => Date.parse(a.date) - Date.parse(b.date) || a.value - b.value);
console.log(res);
<script>
let arr = [{
    date: '2018-06-19 12:05:43.232Z',
    value: 3
  },
  {
    date: '2018-06-20 12:05:43.232Z',
    value: 4
  },
  {
    date: '2018-06-18 12:05:43.232Z',
    value: 2
  },
  {
    date: '2018-06-20 12:05:43.232Z',
    value: 4
  },
  {
    date: '2018-06-19 12:05:43.232Z',
    value: 5
  },
  {
    date: '2018-06-18 12:05:43.232Z',
    value: 5
  },
  {
    date: '2018-06-20 12:05:43.232Z',
    value: 5
  },
  {
    date: '2018-06-19 12:05:43.232Z',
    value: 4
  },
]
</script>

答案 1 :(得分:0)

您可以使用lodash库执行此操作。如果您查看orderBy函数的文档,您会发现它正是您所需要的。

let arr = [  
  {"date": "2018-06-19 12:05:43.232Z", "value": 3},
  {"date": "2018-06-20 12:05:43.232Z", "value": 4},  
  {"date": "2018-06-18 12:05:43.232Z", "value": 2},  
  {"date": "2018-06-20 12:05:43.232Z", "value": 4}, 
  {"date": "2018-06-19 12:05:43.232Z", "value": 5},     
  {"date": "2018-06-18 12:05:43.232Z", "value": 5},  
  {"date": "2018-06-20 12:05:43.232Z", "value": 5},  
  {"date": "2018-06-19 12:05:43.232Z", "value": 4}  
]

在阵列上应用_orderBy,如下所示:

_.orderBy(arr, ['date', 'value'], ['asc', 'asc']);

将为您提供所需的结果。

检查以下示例:

let arr = [  
  {"date": "2018-06-19 12:05:43.232Z", "value": 3},
  {"date": "2018-06-20 12:05:43.232Z", "value": 4},  
  {"date": "2018-06-18 12:05:43.232Z", "value": 2},  
  {"date": "2018-06-20 12:05:43.232Z", "value": 4}, 
  {"date": "2018-06-19 12:05:43.232Z", "value": 5},     
  {"date": "2018-06-18 12:05:43.232Z", "value": 5},  
  {"date": "2018-06-20 12:05:43.232Z", "value": 5},  
  {"date": "2018-06-19 12:05:43.232Z", "value": 4}  
]



console.log(_.orderBy(arr, ['date', 'value'], ['asc', 'asc']))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>