我有一个数组,其中每10秒包含一个特定值的快照:
arr = [
{snapshotAt: "2019-08-20T18:23:46.3915797-07:00", amount: 5233123},
{snapshotAt: "2019-08-20T18:23:56.4835221-07:00", amount: 5233221},
...
{snapshotAt: "2019-08-21T10:54:38.9182797-07:00", amount: 5594822},
{snapshotAt: "2019-08-21T10:54:48.3915817-07:00", amount: 5595115},
{snapshotAt: "2019-08-21T10:54:58.1827367-07:00", amount: 5595350},
]
我需要每分钟获取最大金额:
reducedSnapshot: [
{snapshotAt: "2019-08-20T18:23:00-07:00", amount: 5593221},
...
{snapshotAt: "2019-08-21T10:54:00-07:00", amount: 5595350},
]
答案 0 :(得分:1)
到目前为止,我有这个。它似乎正在工作。我还没有测试边缘情况:
arr = [
{snapshotAt: new Date("2019-08-20T18:23:46.3915797-07:00"), amount: 5233123},
{snapshotAt: new Date("2019-08-20T18:23:56.4835221-07:00"), amount: 5233221},
{snapshotAt: new Date("2019-08-21T10:54:38.9182797-07:00"), amount: 5594822},
{snapshotAt: new Date("2019-08-21T10:54:48.3915817-07:00"), amount: 5595115},
{snapshotAt: new Date("2019-08-21T10:54:58.1827367-07:00"), amount: 5595350},
];
function groupBy(snapshots) {
let map = new Map();
snapshots.forEach(snapshot => {
let key = `${snapshot.snapshotAt.getFullYear()}-${snapshot.snapshotAt.getMonth()+1}-${snapshot.snapshotAt.getDate()} ${snapshot.snapshotAt.getHours()}:${snapshot.snapshotAt.getMinutes()}`;
let val = map.get(key);
if(!val){
map.set(key, {snapshotAt: new Date(key), amount: snapshot.amount });
}
else{
val.amount = (snapshot.amount > val.amount)? snapshot.amount : val.amount;
}
});
return Array.from(map.values());
}
console.log(groupBy(arr));
output:
[ { snapshotAt: 2019-08-21T01:23:00.000Z, amount: 5233221 },
{ snapshotAt: 2019-08-21T17:54:00.000Z, amount: 5595350 } ]