以日期为键对地图进行排序 (javascript)

我想在 javascript 中对地图进行排序。地图看起来像这样:


0: { key: '2020-09-29', value: { foo: 1, bar: 2} },

1: { key: '2020-09-01', value: { foo: 3, bar: 4} },

2: { key: '2020-09-08', value: { foo: 5, bar: 6} }

等等..


我找不到解决方案,有人可以给我提示吗?


我已经尝试过这样的事情:


days_map = new Map([...days_map].sort(function(key, value) { return new Date(key); }));

但它没有对地图进行排序。


谢谢


小唯快跑啊
浏览 134回答 2
2回答

噜噜哒

您可以使用键对数组进行排序String#localeCompare。let map = new Map([['2020-09-29', { foo: 1, bar: 2 }], ['2020-09-01', { foo: 3, bar: 4 }], ['2020-09-08', { foo: 5, bar: 6 }]]),    sorted = new Map(Array.from(map).sort(([a], [b]) => a.localeCompare(b)));console.log([...map]);console.log([...sorted]);.as-console-wrapper { max-height: 100% !important; top: 0; }

BIG阳

var input = [{&nbsp; &nbsp; key: '2020-09-29',&nbsp; &nbsp; value: {&nbsp; &nbsp; &nbsp; foo: 1,&nbsp; &nbsp; &nbsp; bar: 2&nbsp; &nbsp; }&nbsp; },&nbsp; {&nbsp; &nbsp; key: '2020-09-01',&nbsp; &nbsp; value: {&nbsp; &nbsp; &nbsp; foo: 3,&nbsp; &nbsp; &nbsp; bar: 4&nbsp; &nbsp; }&nbsp; },&nbsp; {&nbsp; &nbsp; key: '2020-09-08',&nbsp; &nbsp; value: {&nbsp; &nbsp; &nbsp; foo: 5,&nbsp; &nbsp; &nbsp; bar: 6&nbsp; &nbsp; }&nbsp; }]input.sort((a, b) => {&nbsp; const first = a.key&nbsp; const second = b.key&nbsp;&nbsp;&nbsp; return first > second ? 1 : (first < second ? -1 : 0)});console.log(input);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript