How to loop over from an array as long as the dates are the same?

  • 0
    I have objects that have recording times. There are a lot of objects, so I consider it resource-intensive to loop through all the records. Actually the question: how to iterate over the array and get out of it, provided that the date is taken from the most recent record.
    For example, you need to display in the console like this
    "10/18/2020 - only 2 records, id-2 and id-3"

    example array:
    var array = [
    {id: 1, date: 1600329223354}, //17.09.2020
    {id: 2, date: 1603001365232}, //18.10.2020
    {id: 3, date: 1603001365297} //18.10.2020
    ];
    JavaScript Anonymous, May 1, 2020

  • 2 Answers
  • 0
    First, the array must be sorted by date, if it is not already ordered. In any programming language there is some sort () function, which can somehow be set how to compare objects to be sorted (here you only need to compare dates).



    Your condition is not very clear, but here's how to group the array by date:

    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 simply 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 off 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 keep in mind, this code does not work on an empty array. It is necessary to check this case separately.
    Anonymous

  • 0
    I think first you 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 cutoff, make sure that we do not skip the required timestamp period - 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 number is skipped, and then we take this interval, and 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 a for (..; ..; ..) loop until we hit the boundaries of the interval on both sides
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!