提问人:Nguyễn Yor 提问时间:10/26/2023 最后编辑:Nguyễn Yor 更新时间:10/26/2023 访问量:45
按范围对项目进行分组,而时间仍必须符合时间 [重复]
Group items by range, while the time must still comply with time [duplicate]
问:
按范围和时间对项目进行分组仍必须令人满意 我尝试了很多方法,但我所取得的成就并不是我所期望的
我有数组
const data = [
{
detected_time: 1,
estimated_stay_time: 300,
extension_window: 100000
},
{
detected_time: 2,
estimated_stay_time: 330000,
extension_window: 100000
},
{
detected_time: 3,
estimated_stay_time: 130000,
extension_window: 100000
},
{
detected_time: 4,
estimated_stay_time: 150000,
extension_window: 100000
},
{
detected_time: 5,
estimated_stay_time: 3000,
extension_window: 100000
},
{
detected_time: 6,
estimated_stay_time: 591988,
extension_window: 100000
},
{
detected_time: 7,
estimated_stay_time: 663913,
extension_window: 100000
}
];
现在我想按字段estimated_stay_time对项目进行分组,分组范围为 100000,但仍符合字段detected_time的顺序
例如,如果下一个项目的estimated_stay_time字段大于指定范围,则将从那里对其进行分组。
范围必须向前,而不是向后
我想要的输出是
[
[
{
detected_time: 1,
estimated_stay_time: 300,
extension_window: 100000
},
],
[
{
detected_time: 2,
estimated_stay_time: 330000,
extension_window: 100000
},
],
[
{
detected_time: 3,
estimated_stay_time: 130000,
extension_window: 100000
},
{
detected_time: 4,
estimated_stay_time: 150000,
extension_window: 100000
},
],
[
{
detected_time: 5,
estimated_stay_time: 3000,
extension_window: 100000
},
],
[
{
detected_time: 6,
estimated_stay_time: 591988,
extension_window: 100000
},
{
detected_time: 7,
estimated_stay_time: 663913,
extension_window: 100000
}
]
]
答:
0赞
Nina Scholz
10/26/2023
#1
您可以构建一个增量并检查间隔。如果在外面,请带一个新组。
const
data = [{ detected_time: 1, estimated_stay_time: 300, extension_window: 100000 }, { detected_time: 2, estimated_stay_time: 330000, extension_window: 100000 }, { detected_time: 3, estimated_stay_time: 130000, extension_window: 100000 }, { detected_time: 4, estimated_stay_time: 150000, extension_window: 100000 }, { detected_time: 5, estimated_stay_time: 3000, extension_window: 100000 }, { detected_time: 6, estimated_stay_time: 591988, extension_window: 100000 }, { detected_time: 7, estimated_stay_time: 663913, extension_window: 100000 }],
result = data.reduce((r, o, i, a) => {
const delta = o.estimated_stay_time - (a[i - 1]?.estimated_stay_time ?? 0);
if (!i || delta < 0 || delta > o.extension_window) r.push([o]);
else r.at(-1).push(o);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
评论
0赞
Nguyễn Yor
10/26/2023
非常感谢,这正是我所需要的
0赞
Nguyễn Yor
10/31/2023
你好 NinaSchlz,我的问题是根据extentions_window范围,组略有变化,它们必须具有相同的zone_id。使用您的代码,我不知道如何重用它们。
评论
estimated_staytime
x
extension_window
y
estimated_staytime
x
x+y
extension_window
{st: 10, ew: 5}, {st, 11, ew 3}, {st: 14, ew 7}, {st: 16, ew: 3}
st in 10 .. 15
ew: 7