我有以下对象数组:

var transactions = [
[
    {"id":1,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:33:00.000Z"},
    {"id":2,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:33:50.000Z"},
    {"id":3,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:34:30.000Z"},
    {"id":4,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:36:00.000Z"}
],
[
    {"id":5,"sourceAccount":"A","targetAccount":"C","amount":250,"category":"other","time":"2018-03-02T10:33:00.000Z"},
    {"id":6,"sourceAccount":"A","targetAccount":"C","amount":250,"category":"other","time":"2018-03-02T10:33:05.000Z"}
]
]


我需要连续比较每个对象的time属性,并仅保留每个连续事务之间的时间差小于1分钟的那些属性。

数组格式应该保持不变,这是我尝试过的方法,但是没有运气,没有用。有什么问题?

 var newArray = transactions.map(g => g.reduce((r, o, i, a) => {
        if (!i || new Date(o.time).getTime() - new Date(a[i - 1].time).getTime() >= 60000) {
            r.push([o]);
        } else {
            r[r.length - 1].push(o);
        }
        return r;
    }, []));


预期的输出是这样的:

var output = [
[
    {"id":1,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:33:00.000Z"},
    {"id":2,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:33:50.000Z"},
    {"id":3,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:34:30.000Z"}
],
[
    {"id":5,"sourceAccount":"A","targetAccount":"C","amount":250,"category":"other","time":"2018-03-02T10:33:00.000Z"},
    {"id":6,"sourceAccount":"A","targetAccount":"C","amount":250,"category":"other","time":"2018-03-02T10:33:05.000Z"}
]
]

最佳答案

您可以Array#map您的源数组,并且在每次迭代中,通过将当前元素的时间与上一个元素的时间进行比较,Array#filter所需的元素。



var transactions = [[{"id":1,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:33:00.000Z"},{"id":2,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:33:50.000Z"},{"id":3,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:34:30.000Z"},{"id":4,"sourceAccount":"A","targetAccount":"B","amount":100,"category":"food","time":"2018-03-02T10:36:00.000Z"}],[{"id":5,"sourceAccount":"A","targetAccount":"C","amount":250,"category":"other","time":"2018-03-02T10:33:00.000Z"},{"id":6,"sourceAccount":"A","targetAccount":"C","amount":250,"category":"other","time":"2018-03-02T10:33:05.000Z"}]];

var result = transactions.map((tr, i) => {
  return tr.filter((t, j) => {
    if (transactions[i][j - 1]) {
      var d1 = new Date(t.time);
      var d2 = new Date(transactions[i][j - 1].time);
      return (d1.getTime() - d2.getTime()) <= 60000;
    }

    return true;
  });
});

console.log(result);

07-24 09:47
查看更多