Answer the question
In order to leave comments, you need to log in
How to iterate from an array as long as the dates match?
I have objects that have write times. There are a lot of objects, so I consider it resource-consuming to cycle through all the records. Actually the question is: how to iterate over the array and exit it, provided that the date is taken from the most recent entry.
For example, you need to output in the console like this
"10/18/2020 - 2 entries in total, id-2 and id-3"
var array = [
{id: 1, date: 1600329223354}, //17.09.2020
{id: 2, date: 1603001365232}, //18.10.2020
{id: 3, date: 1603001365297} //18.10.2020
];
Answer the question
In order to leave comments, you need to log in
First, the array must be sorted by dates if it is not already ordered by you. In any programming language, there is some kind of sort() function, which you can somehow specify how to compare the objects to be sorted (here you only need to compare dates).
Your condition is not very clear, but here's how to group an array by dates:
st = 0;
end = 0;
while (st < a.length) {
end = st + 1;
while(end < a.length && a[end].date == a[end-1].date) end++;
console.log(a[st].date);
for (st = st; st < end; st++) {
console.log(a[st].id);
}
}
end = a.length - 1;
st = end - 1;
while (st >= 0 && a[st].date == a[st+1].date) st--;
console.log(a[end].date);
for (st = st+1; st <= end; ++st)
console.log(a[st].id);
I think you first need to find the minimum and maximum timestamp of the date, then try to cut off the pieces with a binary search, remembering the last cursor. with each clipping, make sure that we do not skip the desired period of timestamps - if we are looking for the 18th number, and the previous cursor was on the 19th, and on the current cursor we are on the 17th, then the period for the 18th is slipped, and then we take this interval, and we continue the binary search in it.
when the cursor is on the 18th number in my example, we start going down and up from it with the for(..;..;..) loop until we hit the interval boundaries on both sides
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question