我有一系列要创建时间表的项目。 如果两个或两个以上的项目在x轴上靠在一起(使用'x'值'),则我想将它们合并。
遍历数组并比较'x'属性。如果它们靠在一起,则将其推入两个项目的“实例”字段中。
更改两个项目的日期以使用第一个项目的日期。
我当前的代码将关闭项推入第一个关闭项的“实例”数组中,但不维护该数组中的其他项。我也想不出怎么做日期部分。任何帮助表示赞赏。
const array = [{
"date": "2017-03-04T13:30:00Z",
"id": "7",
"x": "-448.056888554414",
"instances": [{
"date": "2017-03-04T13:30:00Z",
"id": "7",
"x": "-448.056888554414"
}]
},
{
"date": "2017-08-13T13:30:00Z",
"id": "11",
"x": "25.521193637366817",
"instances": [{
"date": "2017-08-13T13:30:00Z",
"id": "11",
"x": "25.521193637366817"
}]
},
{
"date": "2017-08-15T13:30:00Z",
"id": "12",
"x": "31.296536103120246",
"instances": [{
"date": "2017-08-15T13:30:00Z",
"id": "12",
"x": "31.296536103120246"
}]
},
{
"date": "2017-08-20T13:30:00Z",
"id": "13",
"x": "39.95954980175038",
"instances": [{
"date": "2017-08-20T13:30:00Z",
"id": "13",
"x": "39.95954980175038"
}]
}
];
const newArray = [];
newArray.push({
"date": "2018-08-06T13:30:00Z",
"id": "14",
"x": "639.95954980175038",
"instances": [{
"date": "2018-08-06T13:30:00Z",
"id": "14",
"x": "1054"
}]
});
array.reverse().forEach((current: any) => {
const last = newArray[newArray.length - 1];
if (last.x - current.x < 40) {
last.instances.push(current.instances[0]);
} else {
newArray.push(current);
}
});
console.log(newArray);
// this is what I'm trying to create
const desiredArray = [{
"date": "2018-08-06T13:30:00Z",
"id": "14",
"x": "639.95954980175038",
"instances": [{
"date": "2018-08-06T13:30:00Z",
"id": "14",
"x": "1054"
}]
},
{
"date": "2017-08-20T13:30:00Z",
"idDate": "2017-08-20T13:30:00Z",
"id": "13",
"x": "39.95954980175038",
"instances": [{
"date": "2017-08-13T13:30:00Z",
"id": "11",
"x": "25.521193637366817"
},
{
"date": "2017-08-15T13:30:00Z",
"id": "12",
"x": "31.296536103120246"
},
{
"date": "2017-08-20T13:30:00Z",
"id": "13",
"x": "39.95954980175038"
}
]
},
{
"date": "2017-08-20T13:30:00Z",
"idDate": "2017-08-15T13:30:00Z",
"id": "12",
"x": "31.296536103120246",
"instances": [{
"date": "2017-08-13T13:30:00Z",
"id": "11",
"x": "25.521193637366817"
},
{
"date": "2017-08-15T13:30:00Z",
"id": "12",
"x": "31.296536103120246"
},
{
"date": "2017-08-20T13:30:00Z",
"id": "13",
"x": "39.95954980175038"
}
]
},
{
"date": "2017-08-20T13:30:00Z",
"idDate": "2017-08-13T13:30:00Z",
"id": "11",
"x": "25.521193637366817",
"instances": [{
"date": "2017-08-13T13:30:00Z",
"id": "11",
"x": "25.521193637366817"
},
{
"date": "2017-08-15T13:30:00Z",
"id": "12",
"x": "31.296536103120246"
},
{
"date": "2017-08-20T13:30:00Z",
"id": "13",
"x": "39.95954980175038"
}
]
},
{
"date": "2017-03-04T13:30:00Z",
"idDate": "2017-03-04T13:30:00Z",
"id": "7",
"x": "-448.056888554414",
"instances": [{
"date": "2017-03-04T13:30:00Z",
"id": "7",
"x": "448.056888554414"
}]
}
]