如何从TXT文件拆分的数组中过滤指定日期范围的数据?
Absolutely—you’ll need to split each line by the | character first to extract the datestamp value; this is the only reliable way to compare timestamps against your target range. Let’s break down the solution step by step:
Step 1: Prep Your Data
First, clean up the raw array by removing empty lines (like the trailing empty string in your array) and separate the header from the data rows.
Step 2: Extract Datestamps via Splitting
For each data row, split the line using | as the delimiter, then trim whitespace from each segment to get clean values (the datestamp will be the second segment in each split result).
Step 3: Filter by Time Range
Since your timestamps follow a consistent YYYY-MM-DD HH:MM:SSUTC format, you can compare them directly as strings (their lexicographical order matches chronological order). No need to convert to Date objects unless you need to handle time zones or more complex logic later.
Example Code (JavaScript)
If you want to convert the data into structured objects for easier use:
// Your original input array const rawData = [ '|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 |', '' ]; // Define your target time range const startRange = '2019-03-01 10:00:00UTC'; const endRange = '2019-03-02 11:00:00UTC'; // Process and filter the data const filteredRecords = rawData .filter(line => line.trim() !== '') // Remove empty lines .slice(1) // Skip the header row .map(line => { // Split and clean each field const segments = line.split('|').map(seg => seg.trim()); return { datestamp: segments[1], endpoint: segments[2], id: segments[3] }; }) .filter(record => { // Compare timestamps directly as strings return record.datestamp >= startRange && record.datestamp <= endRange; }); console.log(filteredRecords);
If you prefer to keep the original line format (including the header):
const filteredRawLines = rawData .filter(line => line.trim() !== '') .filter((line, idx) => { if (idx === 0) return true; // Keep the header const segments = line.split('|').map(seg => seg.trim()); const datestamp = segments[1]; return datestamp >= startRange && datestamp <= endRange; }); console.log(filteredRawLines);
Key Notes
- Splitting by
|is non-negotiable here—you can’t filter based on the timestamp unless you extract it from each line. - Using string comparison works because your timestamp format is standardized (year first, then month, day, etc.). If you had a different format, you’d need to convert to
Dateobjects for accurate comparisons.
内容的提问来源于stack exchange,提问作者Anna Almestal

