How to find all elements in array included by range efficiently?

I have a big array of date elements, array is already sorted.

[2020.12.31, 2020.12.31, 2021.01.03, 2021.01.04, 2021.01.04, 2021.02.16, 2021.06.16] etc.

And there is some range: [2021.01.03, 2021.05.15]

I need to find all elements which are included by this range: [2021.01.03, 2021.01.04, 2021.01.04, 2021.02.16]

I coded one solution, but it is not efficient for big array. I think this can be solved by using binary search, but I don’t have idea how to.

My code:

       let i = 0,
        j = eventsId.length - 1,
      while (!startIndex && !endIndex && i < j) {
        if (!startIndex) {
          if (
            new Date(events[eventsId[i]].startDate) >= new Date(interval.start)
            startIndex = i
          else i++
        if (!endIndex) {
          if (new Date(events[eventsId[j]].startDate) <= new Date(interval.end))
            endIndex = j
          else j--
      if (startIndex && endIndex) {
        return eventsId.slice(startIndex, endIndex + 1)

198 thoughts on “How to find all elements in array included by range efficiently?”

  1. i need loan money, i need a loan now. i need a loan with poor credit need loan need a loan i need an emergency loan now, cash advance loans up to $5000, cash advance online, cash advances, online cash advance loans unemployed. Money is typically viewed banking, provides business loans.


Leave a Comment