首页 > 解决方案 > 查找数组中特定项目之间的差异

问题描述

我有一个类似于这样的数据对象:

 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)

任何帮助将不胜感激,因为我碰壁了!

标签: javascriptarraysreactjssorting

解决方案


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>


推荐阅读