Let's say I have this:
const list1 = [{id: 1, lastModified: 1513016523527}, {id: 2, lastModified: 1513016523529}];
const list2 = [{id: 1, lastModified: 1513016577222}, {id: 3, lastModified: 1513016605676}];
and I consider two items to be equal if they have the same ID, even if the lastModified is different. How do I merge these two lists, ignoring duplicates?
Expected result (note that there is only one object with id: 1):
[{id: 1, lastModified: 1513016523527}, {id: 3, lastModified: 1513016605676}, {id: 2, lastModified: 1513016523529}]
(In the case of duplicates, I don't care which lastModified ends up in the merged array. Also, I don't care about the order that the results are in.)
I have two ideas: the first is to sort the two lists and pop from the ends like in merge sort, with the added condition that after popping an item, we don't append it to the merged list if it's the same as the last item we appended to the merged list.
The second idea is to put every item in both lists in a hashmap with the id as the key, and then iterate over the keys in the map to create the list.
However, I'm wondering if there's a simpler way to do this from a code readability perspective, like a built-in merge function that takes a custom equality comparison function or something. Also, time complexity should be better than O(n^2).
I've looked at the answers here, but they either don't support custom comparison functions, aren't vanilla javascript, or have bad time complexity: How to merge two arrays in JavaScript and de-duplicate items. It's the same for this one as well: Merge 2 arrays of objects