// My data is like this
const data = [
{
id: 1,
color: "red",
time: [
{ start: new Date("2021-4-3"), end: new Date("2021-4-4") },
{ start: new Date("2021-4-2"), end: new Date("2021-4-3") }
]
},
{
id: 2,
color: "blue",
time: [
{ start: new Date("2021-4-2"), end: new Date("2021-4-3") }
]
}
]我想对时间进行排序,然后像下面这样调整数据。
[
{ id: "1-0", start: new Date("2021-4-2"), end: new Date("2021-4-3"), color: "red" },
{ id: "1-1", start: new Date("2021-4-3"), end: new Date("2021-4-4"), color: "red" },
{ id: "2-0", start: new Date("2021-4-2"), end: new Date("2021-4-3"), color: "blue" },
]我想知道是否有更好的算法来处理这种情况?下面是我的尝试。(我还尝试了ES6语法reduce、flatMap和flat,但我找不到更好的方法来处理这种情况。)
let arr = [];
let timeLength = 0;
for (let i = 0; i < data.length; i++) {
timeLength = data[i].time.length;
if (timeLength !== 1) {
data[i].time.sort((a, b) => new Date(a.start) - new Date(b.start)); // sort time
}
for (let j = 0; j < timeLength; j++) {
arr.push({
id: data[i].id + "-" + i,
color: data[i].color,
start: data[i].time[j].start,
end: data[i].time[j].end,
});
}
}发布于 2021-04-02 14:09:17
我在您的代码中看到了一个实质性的慢速:在sort调用中,您正在重复调用new Date(...)。没有理由这样做。您的字段已经是日期,因此您可以按原样使用它们。我更喜欢使用flatMap和map,所以我的版本如下所示:
const convert = (data) =>
data .flatMap (
({time, ...rest}) => [...time] .sort ((a, b) => a .start - b .start)
.map (t => ({...rest, ...t}))
)
const data = [{id: 1, color: "red", time: [{start: new Date("2021-4-3"), end: new Date("2021-4-4")}, {start: new Date("2021-4-2"), end: new Date("2021-4-3")}]}, {id: 2, color: "blue", time: [{start: new Date("2021-4-2"), end: new Date("2021-4-3")}]}]
console .log (convert (data)).as-console-wrapper {max-height: 100% !important; top: 0}
如果您使用的不是Date对象,而是具有2021-04-03格式的字符串,那么您也可以直接排序,而无需任何Date实例化:
[...time] .sort (({start: s1}, {start: s2}) => s1 < s2 ? -1 : s1 > s2 ? 1 : 0)如果输入对象完全没有用处,您可以跳过time的浅克隆,将[...time] .sort (...)替换为time .sort (...)。但这不会带来什么好处,你的原始数据的变异可能会有问题。
https://stackoverflow.com/questions/66913907
复制相似问题