我试图对一个ISO日期数组进行排序。
arr = ["2019-12-30T00:00:00.000Z", "2020-01-06T00:00:00.000Z", "2020-01-13T00:00:00.000Z", "2020-01-20T00:00:00.000Z", "2020-01-27T00:00:00.000Z", "2020-02-03T00:00:00.000Z", "2020-02-10T00:00:00.000Z", "2020-02-17T00:00:00.000Z", "2020-02-24T00:00:00.000Z", "2020-03-02T00:00:00.000Z", "2020-03-09T00:00:00.000Z", "2020-03-16T00:00:00.000Z", "2020-03-23T00:00:00.000Z", "2020-03-30T00:00:00.000Z", "2020-04-06T00:00:00.000Z", "2020-04-13T00:00:00.000Z", "2020-04-20T00:00:00.000Z", "2020-04-27T00:00:00.000Z", "2020-05-04T00:00:00.000Z"]
我正在尝试使用以下方法对分组数据进行排序。
for (a in get_grouped) {
cat.forEach(t => {
if (!get_grouped[a].some(v => v.type == t)) {
get_grouped[a].push({
"date": get_grouped[a][0].date,
"metric": 0,
"type": t
});
}
});
get_grouped[a].sort((a, b) => arr.indexOf(a.date)-arr.indexOf(b.date));
}
get_grouped:
(3) [{…}, {…}, {…}]
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2: {date: "2020-01-01", metric: 0, type: "Jeeves"}
length: 3
__proto__: Array(0)
(index):98
(3) [{…}, {…}, {…}]
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 0, type: "Bing"}
2: {date: "2020-01-02", metric: 32, type: "Jeeves"}
length: 3
__proto__: Array(0)
(index):98
(3) [{…}, {…}, {…}]
0: {date: "2020-01-03", metric: 30, type: "Google"}
1: {date: "2020-01-03", metric: 24, type: "Bing"}
2: {date: "2020-01-03", metric: 0, type: "Jeeves"}
这种排序方式在以下情况下可以正常工作 cat
是一个字符串数组。当它是一个ISO日期的数组时,我如何对它进行排序?我如何使用Moment JS来做?
通过拥有 ISO 8601 字符串,你可以采用标准的方法,用 Array#sort
,它是按字符串排序的。
var array = ["2019-12-30T00:00:00.000Z", "2020-01-06T00:00:00.000Z", "2020-01-13T00:00:00.000Z", "2020-01-20T00:00:00.000Z", "2020-01-27T00:00:00.000Z", "2020-02-03T00:00:00.000Z", "2020-02-10T00:00:00.000Z", "2020-02-17T00:00:00.000Z", "2020-02-24T00:00:00.000Z", "2020-03-02T00:00:00.000Z", "2020-03-09T00:00:00.000Z", "2020-03-16T00:00:00.000Z", "2020-03-23T00:00:00.000Z", "2020-03-30T00:00:00.000Z", "2020-04-06T00:00:00.000Z", "2020-04-13T00:00:00.000Z", "2020-04-20T00:00:00.000Z", "2020-04-27T00:00:00.000Z", "2020-05-04T00:00:00.000Z"]
array.sort();
console.log(array);
对于按给定日期数组的indic进行排序,你可以取一个格式与数据结构相匹配的对象进行排序,并取索引作为排序值。
var array = ["2019-12-30T00:00:00.000Z", "2020-01-06T00:00:00.000Z", "2020-01-13T00:00:00.000Z", "2020-01-20T00:00:00.000Z", "2020-01-27T00:00:00.000Z", "2020-02-03T00:00:00.000Z", "2020-02-10T00:00:00.000Z", "2020-02-17T00:00:00.000Z", "2020-02-24T00:00:00.000Z", "2020-03-02T00:00:00.000Z", "2020-03-09T00:00:00.000Z", "2020-03-16T00:00:00.000Z", "2020-03-23T00:00:00.000Z", "2020-03-30T00:00:00.000Z", "2020-04-06T00:00:00.000Z", "2020-04-13T00:00:00.000Z", "2020-04-20T00:00:00.000Z", "2020-04-27T00:00:00.000Z", "2020-05-04T00:00:00.000Z"],
indices = array.reduce((r, d, i) => (r[d.slice(0, 10)] = i + 1, r), {});
console.log(indices);
// for sorting take
// get_grouped[a].sort((a, b) => indices[a.date] - indices[b.date]);