Merge lists and dedupe by key while keeping keyless items
An activity feed loads pages from the server while new posts keep arriving, so the same post often shows up on two pages. Before rendering, the client merges all loaded pages into one list and drops the repeats. Posts that are still being written locally have no id yet; they must never be dropped.
Implement mergeUniqueBy(lists, key).
mergeUniqueBy(lists, key) // => new array of items
lists is an array of arrays of items (for example, the loaded pages in order).key says how to identify an item. It is either:
(item) => key, or'id' or 'author.handle' (dot-separated). If any step of the path is null or undefined, the key is undefined.Set membership (SameValueZero): NaN equals NaN, 0 equals -0, '1' is different from 1, and objects are equal only if they are the same object.null or undefined are always kept, every time they appear.key is a function, call it exactly once per item, in the order the items are visited.lists or the items.const page1 = [{ id: 1, text: 'hi' }, { id: 2, text: 'yo' }];
const page2 = [{ id: 2, text: 'yo (edited)' }, { id: 3, text: 'hey' }];
mergeUniqueBy([page1, page2], 'id');
// => [{ id: 1, text: 'hi' }, { id: 2, text: 'yo' }, { id: 3, text: 'hey' }]
mergeUniqueBy([['apple', 'Avocado'], ['banana', 'avocado']], (word) => word[0].toLowerCase());
// => ['apple', 'banana']
const drafts = [{ text: 'draft A' }, { id: 7, text: 'sent' }];
mergeUniqueBy([drafts, [{ text: 'draft B' }, { id: 7, text: 'dup' }]], 'id');
// => [{ text: 'draft A' }, { id: 7, text: 'sent' }, { text: 'draft B' }]
mergeUniqueBy([[{ author: { handle: 'ada' } }, { author: { handle: 'ada' } }]], 'author.handle');
// => [{ author: { handle: 'ada' } }]
mergeUniqueBy([], 'id'); // => []