AHi*_*son 1 javascript arrays lodash
我有一个包含两种不同类型对象的数组,每个对象都有自己的日期字段,其中键是不同的.见下文:
const array = [
{ id: 1, occurs_at: '2017-02-03T07:00:01.000Z' },
{ id: 2, occurs_at: '2017-02-03T10:00:01.000Z' },
{ id: 3, start: '2017-02-03T04:00:01.000Z' },
{ id: 4, start: '2017-02-03T06:00:01.000Z' },
];
Run Code Online (Sandbox Code Playgroud)
我试图按升序排列它们,但我似乎无法找到解决方案.我一直在使用Lodash进行基于单个属性的其他排序.有什么想法吗?
您可以测试所需属性并仅使用具有真实值的属性.
var array = [{ id: 1, occurs_at: '2017-02-03T07:00:01.000Z' }, { id: 2, occurs_at: '2017-02-03T10:00:01.000Z' }, { id: 3, start: '2017-02-03T04:00:01.000Z' }, { id: 4, start: '2017-02-03T06:00:01.000Z' }];
array.sort(function (a, b) {
return (a.occurs_at || a.start).localeCompare(b.occurs_at || b.start);
});
console.log(array);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |