So consider the following image of an array of objects where its date: array
因此,请考虑以下对象数组的图像,其日期为:array
It's clear to see that this array is out of order, there are tons of examples of sorting an array of objects where there is a date key with a value of the date. But there seem to be no example wheres I can sort this array of objects where the key of the object is the date.
很明显,这个数组是乱序的,有大量的对象数组排序的例子,其中有一个日期键,其值为日期。但似乎没有例子我可以对这个对象的数组进行排序,其中对象的键是日期。
Ideas?
This answer is the closest answer I could find but again my date, as you can see if the key of the object.
这个答案是我能找到的最接近的答案,但又是我的约会,因为你可以看到对象的关键。
2 个解决方案
#1
0
Consider:
data = [
{[new Date(2014, 1, 2)]: 1},
{[new Date(2013, 2, 3)]: 1},
{[new Date(2016, 3, 4)]: 1},
{[new Date(2014, 4, 5)]: 1},
{[new Date(2015, 1, 6)]: 1},
{[new Date(2016, 2, 2)]: 1},
{[new Date(2014, 3, 3)]: 1},
{[new Date(2015, 4, 4)]: 1},
{[new Date(2013, 5, 5)]: 1}
];
result = data
.map(obj => [Date.parse(Object.keys(obj)[0]), obj])
.sort((x, y) => x[0] - y[0])
.map(x => x[1]);
console.log(result);
This uses a technique called "decorate-sort-undecorate" oder Schwartzian transform.
这使用了一种称为“decorate-sort-undecorate”或Schwartzian变换的技术。
#2
0
Alternative to georg's way.
替代georg的方式。
data = [
{[new Date(2014, 1, 2)]: 1},
{[new Date(2013, 2, 3)]: 1},
{[new Date(2016, 3, 4)]: 1},
{[new Date(2014, 4, 5)]: 1},
{[new Date(2015, 1, 6)]: 1},
{[new Date(2016, 2, 2)]: 1},
{[new Date(2014, 3, 3)]: 1},
{[new Date(2015, 4, 4)]: 1},
{[new Date(2013, 5, 5)]: 1}
];
data.sort((a, b) =>
Date.parse(Object.keys(a)[0]) -
Date.parse(Object.keys(b)[0]))
console.log(data)
#1
0
Consider:
data = [
{[new Date(2014, 1, 2)]: 1},
{[new Date(2013, 2, 3)]: 1},
{[new Date(2016, 3, 4)]: 1},
{[new Date(2014, 4, 5)]: 1},
{[new Date(2015, 1, 6)]: 1},
{[new Date(2016, 2, 2)]: 1},
{[new Date(2014, 3, 3)]: 1},
{[new Date(2015, 4, 4)]: 1},
{[new Date(2013, 5, 5)]: 1}
];
result = data
.map(obj => [Date.parse(Object.keys(obj)[0]), obj])
.sort((x, y) => x[0] - y[0])
.map(x => x[1]);
console.log(result);
This uses a technique called "decorate-sort-undecorate" oder Schwartzian transform.
这使用了一种称为“decorate-sort-undecorate”或Schwartzian变换的技术。
#2
0
Alternative to georg's way.
替代georg的方式。
data = [
{[new Date(2014, 1, 2)]: 1},
{[new Date(2013, 2, 3)]: 1},
{[new Date(2016, 3, 4)]: 1},
{[new Date(2014, 4, 5)]: 1},
{[new Date(2015, 1, 6)]: 1},
{[new Date(2016, 2, 2)]: 1},
{[new Date(2014, 3, 3)]: 1},
{[new Date(2015, 4, 4)]: 1},
{[new Date(2013, 5, 5)]: 1}
];
data.sort((a, b) =>
Date.parse(Object.keys(a)[0]) -
Date.parse(Object.keys(b)[0]))
console.log(data)