// 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") } ] } ]
And I want to sort time then adjust the data like below.
[ { 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" }, ]
I want to know is there have better algorithm to handle this situation? Below is my attempt. (I also attempted ES6 syntax reduce
, flatMap
and flat
, but I can't find the better way to handle this situation.)
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, }); } }
https://stackoverflow.com/questions/66913907/flatten-and-sort-nested-array-of-object-by-its-array-value April 02, 2021 at 10:57AM
没有评论:
发表评论