【发布时间】:2022-01-02 07:52:03
【问题描述】:
只有值大于或等于阈值的元素必须保留在数组中。然后必须创建一个包含多个对象的新数组。这些对象中的每一个都有两个属性,开始和结束。
如果一行中有多个元素(时间戳相隔 10 分钟),它们将被分组到同一个对象中。其中起始值将是第一个元素的时间戳,结束值将是组中最后一个元素的时间戳值加上 10 分钟。
如果后面没有几个元素,则起始值为时间戳,结束值为时间戳加 10 分钟。
const data = [{
timestamp: '2021-11-23T14:00:00+0000',
amount: 21
},
{
timestamp: '2021-11-23T14:10:00+0000',
amount: 27
},
{
timestamp: '2021-11-23T14:20:00+0000',
amount: 31
},
{
timestamp: '2021-11-23T14:30:00+0000',
amount: 29
},
{
timestamp: '2021-11-23T14:40:00+0000',
amount: 18
},
{
timestamp: '2021-11-23T14:50:00+0000',
amount: 17
},
{
timestamp: '2021-11-23T15:00:00+0000',
amount: 25
},
{
timestamp: '2021-11-23T15:10:00+0000',
amount: 21
}
]
const threshold = 25
const aboveThreshold = data.filter(element => element.amount >= threshold)
const workSchedule = []
for (let i = 0; i < aboveThreshold.length; i++) {
if (i === 0) {
workSchedule.push({
start: aboveThreshold[i].timestamp,
end: aboveThreshold[i + 1].timestamp
})
}
if (i > 0 && i < aboveThreshold.length - 1) {
if (aboveThreshold[i].timestamp.slice(11, 13) === aboveThreshold[i + 1].timestamp.slice(11, 13)) {
workSchedule.push({
start: aboveThreshold[i].timestamp,
end: aboveThreshold[i + 1].timestamp
})
}
}
if (i === aboveThreshold.length - 1) {
workSchedule.push({
start: aboveThreshold[i].timestamp,
end: aboveThreshold[i].timestamp
})
}
}
console.log(workSchedule)
但我想要的最终结果如下:
[
{
start: '2021-11-23T14:10:00+0000',
end: '2021-11-23T14:40:00+0000'
},
{
start: '2021-11-23T15:00:00+0000',
end: '2021-11-23T15:10:00+0000'
}
]
我希望我是清楚的????有没有比我迄今为止所做的更简单、更容易理解/阅读的方法?
【问题讨论】:
-
听起来你的问题不是如何连接数组元素,而是如何过滤或映射它们。请修改您的标题以更具体。不要添加标签。
标签: javascript arrays typescript