O
O
Oposum2020-10-28 12:19:41
JavaScript
Oposum, 2020-10-28 12:19:41

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"

array example:
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

2 answer(s)
W
Wataru, 2020-10-28
@wataru

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);
  }
}

Here we just bite off a piece with the same dates from the array until the array ends. If you only want the last group, then you can only bite once from the end:
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);

Just be aware that this code does not work on an empty array. This case needs to be checked separately.

N
naruto3333, 2020-10-28
@naruto3333

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 question

Ask a Question

731 491 924 answers to any question