从对象数组创建对象的嵌套数组?

时间:2018-07-26 09:58:34

标签: javascript arrays

我有一个对象数组,需要根据时间将其变为嵌套数组

let item = [
  {
    id: 1,
    time: '2018-03-04T07:14:20.000Z'
  },
  {
    id: 2,
    time: '2018-03-04T07:18:30.000Z'
  },
  {
    id: 3,
    time: '2018-03-04T07:14:30.000Z'
  },
  {
    id: 4,
    time: '2018-03-04T07:18:20.000Z'
  },
  {
    id: 5,
    time: '2018-03-04T07:18:40.000Z'
  }
]

我想要的是基于1分钟的时差创建一个嵌套的对象数组。最终结果应该像这样

item = [
 [
  {
    id: 1,
    time: '2018-03-04T07:14:20.000Z'
  },
  {
    id: 3,
    time: '2018-03-04T07:14:30.000Z'
  },
 ],
 [
  {
    id: 3,
    time: '2018-03-04T07:18:20.000Z'
  },
  {
    id: 4,
    time: '2018-03-04T07:18:30.000Z'
  },
  {
    id: 5,
    time: '2018-03-04T07:18:40.000Z'
  }
 ]
]

我尝试使用arr.reduce(),但是我对如何做到这一点有些困惑。

1 个答案:

答案 0 :(得分:1)

您可以使用reduce使用年,月,日,小时和分钟作为键(前16个字符)将数组汇总为一个对象。

使用Object.values将对象转换为数组。

let item = [{"id":1,"time":"2018-03-04T07:14:20.000Z"},{"id":2,"time":"2018-03-04T07:18:30.000Z"},{"id":3,"time":"2018-03-04T07:14:30.000Z"},{"id":4,"time":"2018-03-04T07:18:20.000Z"},{"id":5,"time":"2018-03-04T07:18:40.000Z"}]

let result = Object.values(item.reduce((c, v) => {
  let k = v.time.substr(0, 16);
  c[k] = c[k] || [];
  c[k].push(v);
  return c;
}, {}));

console.log(result);


您可以使用sort将阵列从最早到最新排列。使用reduce对数组进行分组。

let item = [{"id":1,"time":"2018-03-04T07:14:20.000Z"},{"id":2,"time":"2018-03-04T07:18:30.000Z"},{"id":3,"time":"2018-03-04T07:14:30.000Z"},{"id":4,"time":"2018-03-04T07:18:20.000Z"},{"id":5,"time":"2018-03-04T07:18:40.000Z"},{"id":6,"time":"2018-03-04T07:15:00.000Z"}]

let temp = null;
let result = [...item].sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime())
  .reduce((c, v) => {
    let diff = new Date(v.time).getTime() - new Date(temp).getTime();
    if (temp === null || diff > 60000) c.push([v])
    else c[c.length - 1].push(v);
    temp = v.time;
    return c;
  }, []);


console.log(result);