我有一个这样的对象数组
layerArr = [
{
name: "layer 1"
layerDate: "/Date(6958748400000)/"
layerDateFormatted: "31 December 2018"
etc...
}
{
name: "layer 2"
layerDate: "/Date(9375937500000)/"
layerDateFormatted: "23 December 2017"
etc...
}
{
name: "layer 3"
layerDate: "/Date(1554764400000)/"
layerDateFormatted: "15 January 2018"
etc...
}]
我该如何按日期对layerArr排序,最先显示最新日期? 在此示例中,当第2层正确排序时,我还希望最新日期成为第1层,最旧的日期应成为最后一层。 (上面的示例由值组成)
谢谢
编辑:建议其他线程使用的链接未说明如何更改“名称”,以使最新日期一直变为name ="layer 1"
,直到最早的日期变为最后一层。
答案 0 :(得分:4)
使用Array.sort()
:
layerArr = [
{ name: "layer 1", layerDate: "/Date(6958748400000)/", layerDateFormatted: "31 December 2018" },
{ name: "layer 2", layerDate: "/Date(9375937500000)/", layerDateFormatted: "23 December 2017" },
{ name: "layer 3", layerDate: "/Date(1554764400000)/", layerDateFormatted: "15 January 2018" }
];
sortedLayerArr = layerArr.sort(function(a, b) {
return new Date(a.layerDateFormatted)- new Date(b.layerDateFormatted);
}).map((layer, index) => ({
...layer,
name: `layer ${index + 1}`,
}));
console.log(layerArr);
console.log(sortedLayerArr);