Dedupe an array by SameValueZero, keeping first occurrences
A community app builds each user’s “recently viewed” list by concatenating the forum IDs from several devices. The same forum often shows up more than once, and the list must show each forum only once, in the order it was first seen.
Implement uniqueValues(items). It returns a new array that holds every distinct value of items exactly once, in the order of its first occurrence.
uniqueValues(items) // => new array without duplicates
Set and Array.prototype.includes:
1 and '1' are different, 'a' and 'A' are different.NaN equals NaN, and 0 equals -0.null, undefined, false, 0 and '' are ordinary values: keep one of each.items has no duplicates or is empty. Do not modify items.items can hold tens of thousands of elements, so the solution must run in linear time.uniqueValues([31, 8, 31, 5, 8, 8]); // => [31, 8, 5]
uniqueValues(['js', 'css', 'JS', 'js']); // => ['js', 'css', 'JS']
uniqueValues([1, '1', true, 'true', 1]); // => [1, '1', true, 'true']
uniqueValues([NaN, 4, NaN]); // => [NaN, 4]
uniqueValues([null, undefined, null]); // => [null, undefined]
uniqueValues([]); // => []
const pinned = { id: 'f-9' };
uniqueValues([pinned, { id: 'f-9' }, pinned]);
// => [pinned, { id: 'f-9' }] (the second object is a different reference)