Search code examples
javascriptarraysfilterdate-range

Filter a range of dates from an array


Im reading a .txt file which I've split into an array with lines of info.

This is my original .txt

|datestamp              |endpoint    |id    |
|2019-03-01 09:00:00UTC |/co.html    |12345 |
|2019-03-01 09:00:00UTC |/co.html    |12346 |
|2019-03-01 10:00:00UTC |/co.html    |12345 |
|2019-03-01 10:30:00UTC |/hello.html |12347 |
|2019-03-01 11:00:00UTC |/co.html    |12347 |
|2019-03-02 11:00:00UTC |/co.html    |12348 |
|2019-03-02 12:00:00UTC |/hello.html |12348 |
|2019-03-03 13:00:00UTC |/hello.html |12349 |

so now I've got this array of info:

[
'|datestamp              |endpoint    |id    |',
'|2019-03-01 09:00:00UTC |/co.html    |12345 |',
'|2019-03-01 09:00:00UTC |/co.html    |12346 |',
'|2019-03-01 10:00:00UTC |/co.html    |12345 |',
'|2019-03-01 10:30:00UTC |/hello.html |12347 |',
'|2019-03-01 11:00:00UTC |/co.html    |12347 |',
'|2019-03-02 11:00:00UTC |/co.html    |12348 |',
'|2019-03-02 12:00:00UTC |/hello.html |12348 |',
'|2019-03-03 13:00:00UTC |/hello.html |12349 |',
''
]

So I need to filter on say these datestamps 2019-03-01 10:00:00UTC - 2019-03-02 11:00:00UTC

Do I need to split the array by the pine "|" as well before doing that?

How can I solve this?


Solution

  • No, you don't need to split the array's elements first. You could create Date() objects out of part of the strings and compare these to Date() objects representing your start and end date/times:

    let mydates = [
    '|datestamp              |endpoint    |id    |',
    '|2019-03-01 09:00:00UTC |/co.html    |12345 |',
    '|2019-03-01 09:00:00UTC |/co.html    |12346 |',
    '|2019-03-01 10:00:00UTC |/co.html    |12345 |',
    '|2019-03-01 10:30:00UTC |/hello.html |12347 |',
    '|2019-03-01 11:00:00UTC |/co.html    |12347 |',
    '|2019-03-02 11:00:00UTC |/co.html    |12348 |',
    '|2019-03-02 12:00:00UTC |/hello.html |12348 |',
    '|2019-03-03 13:00:00UTC |/hello.html |12349 |',
    ''
    ]
    
    let startDate = new Date("2019-03-01 10:00:00");
    let endDate = new Date("2019-03-02 11:00:00");
    
    let filtered = mydates.filter(d => new Date(d.substr(1, 19)) >= startDate && new Date(d.substr(1, 19)) <= endDate);
    console.log(filtered);