JavaScript中基于日期字段去重:保留最新日期的重复ID元素
Filter Array to Keep Only the Latest Object per ID
Got it, let's tackle this problem where we need to filter an array of objects, keeping only the one with the most recent date for each unique id. Here's a straightforward, efficient way to do it:
Step-by-Step Approach
- Use a temporary object to track the latest entry for each
id— this lets us look up existing entries in constant time. - Iterate over each item in the input array:
- For each item, check if we already have an entry for its
idin our temporary object. - If we don't, add it immediately.
- If we do, compare the dates: keep the one with the later (more recent) date.
- For each item, check if we already have an entry for its
- Finally, convert the values of our temporary object back into an array — that's our filtered result.
Implementation Code
function filterLatestById(items) { const latestMap = {}; items.forEach(item => { const existing = latestMap[item.id]; // Compare dates directly (YYYY-MM-DD HH:mm:ss strings follow lex order that matches time order) if (!existing || item.date > existing.date) { latestMap[item.id] = item; } }); // Convert the map values to a final array return Object.values(latestMap); } // Test with your sample array let myList = [ { id: "e9519e95-5a10-4274-ac24-de72ad60ffd7", date: "2018-02-21 21:04:13" }, { id: "026e7ecf-d236-4aff-b26d-7546ac85b7d5", date: "2018-02-22 21:04:13" }, { id: "e9519e95-5a10-4274-ac24-de72ad60ffd7", date: "2018-02-23 21:04:13" } ]; const filteredList = filterLatestById(myList); console.log(filteredList);
Output Explanation
Running this code will return the following array (formatted for readability):
[ { id: "e9519e95-5a10-4274-ac24-de72ad60ffd7", date: "2018-02-23 21:04:13" }, { id: "026e7ecf-d236-4aff-b26d-7546ac85b7d5", date: "2018-02-22 21:04:13" } ]
- The duplicate
id"e9519e95-5a10-4274-ac24-de72ad60ffd7" is filtered down to the entry with the latest date (2018-02-23). - The unique
identry is kept as-is.
Notes
- If you want to be extra safe with date comparisons (in case of non-standard date strings), convert the date strings to
Dateobjects before comparing:if (!existing || new Date(item.date) > new Date(existing.date)) { latestMap[item.id] = item; } - This approach runs in O(n) time complexity, where n is the number of items in the input array — very efficient even for large datasets.
内容的提问来源于stack exchange,提问作者steve-o
相关产品推荐
相关产品推荐

