javascript - 查找数组中特定项目之间的差异
问题描述
我有一个类似于这样的数据对象:
const data = [
{
name: "john smith", created_at: "1616846400", description: "clocked in" //7am
},
{
name: "john smith", created_at: "1616853600", description: "clocked Out" //9am
},
{
name: "john smith", created_at: "1616857200", description: "clocked in" //10am
},
{
name: "john smith", created_at: "1616875200", description: "clocked out" //3pm
}
];
这是为了代表一个打卡/打卡打卡表。目标是找出此人在轮班期间被打卡的总时间。
答案是 1 小时。用户在上午 9 点打卡,并在上午 10 点返回,直到他们离开当天才被打卡。
我已经尝试了几种不同的方法,我最近的尝试看起来像这样
const data = [
{
name: "john smith", created_at: "1616846400", description: "clocked in"
},
{
name: "john smith", created_at: "1616853600", description: "clocked Out"
},
{
name: "john smith", created_at: "1616857200", description: "clocked in"
},
{
name: "john smith", created_at: "1616875200", description: "clocked Out"
}
];
let clockOuts = data.filter(function (e) {
return e.description.split(" ").splice(0,2).join(" ") === "clocked Out"
})
let clockIns = data.filter(function (e) {
return e.description.split(" ").splice(0,2).join(" ") === "clocked in"
})
var x = clockOuts.map(function(item, index) {
if (clockIns[index] != null) {
return Math.round(Math.abs(item.created_at - clockIns[index].created_at) / 60)
} else {
return Math.round(Math.abs(item.created_at * 0))
}
})//end clockins Map
console.log(x)
var sum = x.reduce(function(a, b){
return a + b
}, 0)
console.log(sum)
任何帮助将不胜感激,因为我碰壁了!
解决方案
moment.js
会有很大帮助:
const data = [
{name: "john smith", created_at: "1616846400", description:"clocked in"},
{name: "john smith", created_at: "1616853600", description:"clocked Out"},
{name: "john smith", created_at: "1616857200", description: "clocked in"},
{name: "john smith", created_at: "1616875200", description: "clocked out"}
];
let clockedOutTimes = data.reduce((r,i,ix,o)=>{
if (ix===0 || ix === o.length-1) return r;
if (i.description.toLowerCase()==='clocked in') {
let d = moment.unix(parseInt(i.created_at))
.diff(moment.unix(parseInt(o[ix-1].created_at)),'hours');
r=r+d
}
return r;
},0);
console.log(clockedOutTimes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
推荐阅读
- swift - Swift:将整数 x 秒转换为日期,x 秒前
- python - String extraction and http request creation
- excel - How do you paste rows one under the other based on the number given in another sheet?
- amazon-web-services - Spark on DCOS: Make dispatcher reachable from outside the cluster
- angular - Angular InjectionToken 抛出“没有 InjectionToken 提供者”
- java - SprintBootTest - 只创建必要的 bean
- javascript - 如何在 Gitlab CI 中缩小 Javascript 代码?
- python - Python 打印三次,而我调用该函数两次,为什么会这样?
- javascript - 单击事件javascript / jquery多次加载相同的脚本
- abap - 用户出口中的测试失败时取消 Post Good Issue 的处理