gpt4 book ai didi

javascript - 处理一组顺序 bool 值

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:17:02 25 4
gpt4 key购买 nike

很难为这个设置标题和描述,但希望您在阅读代码和注释时能够理解。如果你们有更好的主意,请编辑。

对于这个特定示例,我如何在 javascript 中获取每天每个 truefalse 之间的时间戳总和差异?

作为数组的一般规则:它是否总是循环 true - false。

我的真实数据有点复杂,但我似乎无法正确思考,即使对于这个简化的示例也是如此。

可以是 reduce,可以是 for 循环,任何东西。谢谢!

const data = [
{ day: 'today', timestamp: 11, value: true },
{ day: 'today', timestamp: 13, value: false }, //here should be 13-11
{ day: 'today', timestamp: 14, value: true },
{ day: 'today', timestamp: 17, value: false }, //here should be 17-14
//the sum for today should be 5 (13-11 + 17-14)
{ day: 'tomorrow', timestamp: 9, value: true },
{ day: 'tomorrow', timestamp: 11, value: false }, //here should be 11-9
{ day: 'tomorrow', timestamp: 11, value: true },
{ day: 'tomorrow', timestamp: 16, value: false } //here should be 16-11
//the sum for today should be 7 (11-9 + 16-11)
]

最佳答案

一个简单的 reduce 就可以完成这项工作:只需添加更大的“假”值,然后从总和中删除“真”值即可;)

const data = [
{ day: 'today', timestamp: 11, value: true },
{ day: 'today', timestamp: 13, value: false }, //here should be 13-11
{ day: 'today', timestamp: 14, value: true },
{ day: 'today', timestamp: 17, value: false }, //here should be 17-14
//the sum for today should be 5 (13-11 + 17-14)
{ day: 'tomorrow', timestamp: 9, value: true },
{ day: 'tomorrow', timestamp: 11, value: false }, //here should be 11-9
{ day: 'tomorrow', timestamp: 11, value: true },
{ day: 'tomorrow', timestamp: 16, value: false } //here should be 16-11
//the sum for today should be 7 (11-9 + 16-11)
];

const result = data.reduce((acc, elt) => {
if(!acc[elt.day]) acc[elt.day] = 0;
if(!elt.value) {
acc[elt.day] += elt.timestamp;
} else {
acc[elt.day] -= elt.timestamp;
}
return acc;
},{});
console.log(result);

不要忘记每天将累加器中的值初始化为 0!希望这会有所帮助。

关于javascript - 处理一组顺序 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53872263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com