Reputation: 637
I'm trying to group a list by an ID then inside that new list I'm trying to group a list of values based on that id in a certain time. I've manged to group by the id. I can't figure out what I need to do to group by the duration. Any help please
const data = [
{
"name": "ted",
"id": "1",
"timestamp": 1512709024000
},
{
"name": "seth",
"id": "2",
"timestamp": 1512754631000
},
{
"name": "joe",
"id": "1",
"timestamp": 1512711000000
},
{
"name": "phil",
"id": "2",
"timestamp": 1512754583000
},
{
"name": "kane",
"id": "1",
"timestamp": 1512709065294
},
]
}
{
"result": {
"1": [
{
"duration":18273
"names": ["ted", "joe", "kane"],
"startTime": 1512709065294
}
]
}
}
my efforts so far
const d= data;
const ids= data.reduce((ids, item) => {
const id= (ids[item.id] || [])
id.push(item);
ids[item.id] = id
return ids
}, {})
console.log('visitorIds',visitorIds)
Upvotes: 0
Views: 46
Reputation: 4780
Check this out:
const data = [
{"name": "ted","id": "1","timestamp": 1512709024000},
{"name": "seth","id": "2","timestamp": 1512754631000},
{"name": "joe","id": "1","timestamp": 1512711000000},
{"name": "phil","id": "2","timestamp": 1512754583000},
{"name": "kane","id": "1","timestamp": 1512709065294},
];
const visitors = (data) => {
const groupedData = data.reduce((acc, {id, name, timestamp}) => {
acc[id] = (acc[id])
? {...acc[id], names: [...acc[id].names, name], times: [...acc[id].times, timestamp]}
: {names: [name], times: [timestamp]};
const startTime = Math.min(...acc[id].times);
const finishTime = Math.max(...acc[id].times);
const duration = finishTime - startTime;
acc[id] = {...acc[id], duration, startTime};
return acc;
}, {});
Object.values(groupedData).forEach((obj) => delete obj.times);
return groupedData;
};
console.log(visitors(data));
// {
// '1': {
// names: [ 'ted', 'joe', 'kane' ],
// duration: 1976000,
// startTime: 1512709024000
// },
// '2': {
// names: [ 'seth', 'phil' ],
// duration: 48000,
// startTime: 1512754583000
// }
// }
Upvotes: 1