如何遍历对象数组并过滤出同一小时内的项目

时间:2019-04-08 01:31:10

标签: javascript

我在确定简单的循环和过滤过程中遇到麻烦。

我想遍历此数组并仅返回同一小时内的对象,即8am-9am或10am-11am 不是 8:30 am至9:30 am,这意味着所有8ams在此示例中将返回10 ams。

我有一个像这样的对象数组

let arr = [{
     "action": "Coffee with client", 
     "time": "1/12/2018 08:30:15"},
    {"action": "Check Email", 
     "time": "1/12/2018 08:32:37"},
    {"action": "Order Breakfast Sandwich", 
     "time": "1/12/2018 08:45:43"},
    {"action": "Walk Back To Office", 
     "time": "1/12/2018 09:15:58"},
    {"action": "Attend Morning Meeting", 
     "time": "1/12/2018 10:15:00"}, 
    {"action": "Add Meeting Notes To Calendar", 
     "time": "1/12/2018 10:45:37"}]

我正在努力将这些日期时间字符串归为一组。我已经尝试过将它们转换并执行类似的操作,其中我想做的就是将字符串转换为日期(数字)并比较数组中的每个项目,以查看其是否在同一小时内,是否返回这些项目。我现在迷路了,不胜感激。

const hour = 1000 * 60 * 60;

for(let i = 0; i < arr.length-1; i++) {
   const difference = Date.parse(arr[i+1].time) - 
   Date.parse(arr[i].time)

   if(difference < hour) {
      //return all items in the same hour

   }
 }

1 个答案:

答案 0 :(得分:4)

如果我的理解正确,您可以从日期中获取小时,并创建一个对象为小时,其中每个值都是项目数组。

let arr = [{"action": "Coffee with client", "time": "1/12/2018 08:30:15"},{"action": "Check Email", "time": "1/12/2018 08:32:37"},{"action": "Order Breakfast Sandwich", "time": "1/12/2018 08:45:43"},{"action": "Walk Back To Office", "time": "1/12/2018 09:15:58"},{"action": "Attend Morning Meeting", "time": "1/12/2018 10:15:00"}, {"action": "Add Meeting Notes To Calendar", "time": "1/12/2018 10:45:37"}]

let grouped = arr.reduce((obj, item) => {
  let hour = new Date(item.time).getHours()  // the key for the object
  if (!obj[hour]) obj[hour] = []             // new array if it doesn't exist
  obj[hour].push(item)                       // add item to correct group
  return obj
}, {})

console.log(grouped)

所有8个任命将与grouped[8]等分组。

目前尚不清楚您是否会从一个以上的日期开始约会,以及应该如何处理。