简体   繁体   中英

Sum elements with same value in array of objects

I have an array like this:

[{ "x": 2020-06-27T11:26:00.000Z, "y": 499 },
 { "x": 2020-06-27T11:30:00.000Z, "y": 21 }]

I want to sum the y values that fall within every two hour intervals ( x ). The y values should be combined for intervals 0-2am, 2-4am, 4-6am and so on.

What I've done so far is summing the elements with the same hour:

var t = {};

unsortedData.forEach((v) => {
    if (t[v.x.getHours()]) {
        t[v.x.getHours()] += v.y;
    } else {
        t[v.x.getHours()] = v.y;
    }
});

unsortedData = t;

This returns me something like: {"13": 512, "15": 98..} and so on.

Now, there are a few issues with this code I don't know how to fix.

First is how can I make it work with two-hour intervals instead of the same hour check? Also is there is any way to get a return of a full date instead of just hours?

I will assume in your original data the x properties have Date instances, since you call getHours() on those values.

You can clear the least significant bit of the hour component of your date values, so that they will truncate to a multiple of 2. Use UTC*** methods though, and pass these date components to the Date.UTC method, since your dates were initialised with UTC strings. That gives you a Unix epoch number, which you can use as property for your t object (consider using a more meaningful name).

I would however store the complete object in those t properties, so that at the end you can extract the object values, and end up with exactly the same format as you started with:

 let unsortedData = [ { "x": new Date("2020-06-27T11:26:00.000Z"), "y": 499 }, { "x": new Date("2020-06-27T11:30:00.000Z"), "y": 21 }, { "x": new Date("2020-06-27T12:01:00.000Z"), "y": 15 }, { "x": new Date("2020-06-27T13:59:00.000Z"), "y": 8 }, { "x": new Date("2020-06-27T14:20:00.000Z"), "y": 30 }, { "x": new Date("2020-06-27T14:25:00.000Z"), "y": 1 }, ]; let t = {}; unsortedData.forEach((v) => { let block = Date.UTC( vxgetUTCFullYear(), vxgetUTCMonth(), vxgetUTCDate(), vxgetUTCHours() & 0xFE // ignore last bit of hours binary ); if (t[block]) { t[block].y += vy; } else t[block] = { x: new Date(block), y: vy }; }); let sortedData = Object.values(t); console.log(sortedData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM