I'm looking to find the amount of users based on a ID in a certain time frame
My starting time is 1512709024000 and my end time is 10 mins
I need to group all the users together from the object below
[{
"name": "user1",
"id": "1",
"timestamp": 1512754583000
},
{
"name": "user2",
"id": "1",
"timestamp": 1512754631000
},
{
"name": "user3",
"id": "2",
"timestamp": 1512709065294
},
{
"name": "user4",
"id": "2",
"timestamp": 1512711000000
},
{
"name": "user4",
"id": "1",
"timestamp": 1512754436000
}
]
CodePudding user response:
You can use a filter for this to work
const items = [{
"name": "user1",
"id": "1",
"timestamp": 1512754583000
},
{
"name": "user2",
"id": "1",
"timestamp": 1512754631000
},
{
"name": "user3",
"id": "2",
"timestamp": 1512709065294
},
{
"name": "user4",
"id": "2",
"timestamp": 1512711000000
},
{
"name": "user4",
"id": "1",
"timestamp": 1512754436000
}
];
const timestamp = 1512709024000;
const limit = timestamp 10 * 60 * 1000;
console.log(items.filter((item) => item.timestamp >= timestamp && item.timestamp <= limit));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
const a = [{
"name": "user1",
"id": "1",
"timestamp": 1512754583000
},
{
"name": "user2",
"id": "1",
"timestamp": 1512754631000
},
{
"name": "user3",
"id": "2",
"timestamp": 1512709065294
},
{
"name": "user4",
"id": "2",
"timestamp": 1512711000000
},
{
"name": "user4",
"id": "1",
"timestamp": 1512754436000
}
]
function filterByTimeAndId(arr, startTimeInMs, noOfMinutes, id) {
const noOfMillis = noOfMinutes * 60 * 1000;
const endTimeInMs = startTimeInMs noOfMillis;
return arr.filter(a => a.id === id && a.timestamp >= startTimeInMs && a.timestamp <= endTimeInMs);
}
console.log(filterByTimeAndId(a, 1512709024000, 10, 1));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>