JavaScript多维数组冗余处理求助:合并重复项取最新结束时间
Hey there! Let's work through this problem together. The core goal here is to group entries that share the same start time and name, then keep only the entry with the latest end time from each group. Here's a straightforward, efficient way to do it:
Step 1: Use a grouping object to track entries
We'll create an object where each key is a unique combination of start time + name (like ${startTime}-${name}). This key will let us group identical pairs together, and we'll store the entry with the latest end time for each group as the value.
Step 2: Compare end times accurately
Since your time strings follow the MM/DD/YYYY HH:mm:ss format, converting them to Date objects lets us easily compare which end time is later using their timestamp values (no messy string comparison issues!).
Full Code Example
const rawData = [ ["04/04/2017 11:00:42", "04/04/2018 12:15:37", "Nic"], ["04/04/2017 11:00:42", "04/04/2018 12:16:58", "Nic"], ["06/01/2017 08:30:00", "06/01/2018 09:15:00", "Luna"], ["06/01/2017 08:30:00", "06/01/2018 09:20:00", "Luna"] ]; const filterLatestEntries = (data) => { const entryGroups = {}; data.forEach(entry => { const [startTime, endTime, name] = entry; // Create a unique key for matching start time + name const groupKey = `${startTime}-${name}`; // Convert end time to a timestamp for easy comparison const currentEndTime = new Date(endTime).getTime(); if (!entryGroups[groupKey]) { // If the group doesn't exist yet, add the current entry entryGroups[groupKey] = entry; } else { // Compare with the existing entry's end time const existingEndTime = new Date(entryGroups[groupKey][1]).getTime(); if (currentEndTime > existingEndTime) { // Replace with the entry that has the later end time entryGroups[groupKey] = entry; } } }); // Convert the grouped object back to an array of entries return Object.values(entryGroups); }; const filteredData = filterLatestEntries(rawData); console.log(filteredData); // Expected output: // [ // ["04/04/2017 11:00:42", "04/04/2018 12:16:58", "Nic"], // ["06/01/2017 08:30:00", "06/01/2018 09:20:00", "Luna"] // ]
Quick Notes:
- The
groupKeyensures we only group entries that match both start time and name—exactly the matching logic you need. - Using
Date.getTime()avoids any pitfalls of string-based date comparison (which can fail if date formats vary slightly). - This approach runs in O(n) time, so it's efficient even for larger datasets.
If you need to handle edge cases (like invalid date strings), you could add a quick check to verify the Date conversion works before comparing, but the above code will handle your example perfectly.
内容的提问来源于stack exchange,提问作者shin88

