JavaScriptFundamental (ES6), part 1
Use a Set for unique values in JavaScript
60 A Set for uniqueness and membership
easyDeduplicate a list of arrivals with a Set, ask it about membership, and show that add of something already present changes nothing. Then check what it does with NaN, with -0, and with two equal-looking objects, and build a union and an intersection.
Stuck? Three hints, smallest first
- 1.
[...new Set(list)]is the whole deduplication idiom. - 2.
hasis the membership test, andaddreturns the set so calls chain. - 3. A Set compares like a Map:
NaNequals itself,-0folds into0, objects go by identity.
const arrivals = ['Ikeja', 'Yaba', 'Ikeja', 'Lekki', 'Yaba'];
const unique = [...new Set(arrivals)];
const seen = new Set(arrivals);
const size = seen.size;
const membership = [seen.has('Yaba'), seen.has('Epe')];
const returned = seen.add('Ikeja'); // already there
const sizeAfterAdd = seen.size;
const chained = new Set().add('gari').add('rice').size;
const oddValues = new Set([NaN, NaN, 0, -0]);
const objects = new Set([{ id: 1 }, { id: 1 }]);
const order = [...new Set([3, 1, 3, 2, 1])];
const left = ['gari', 'rice'];
const right = ['rice', 'beans'];
const union = [...new Set([...left, ...right])];
const rightSet = new Set(right);
const intersection = [...new Set(left)].filter((item) => rightSet.has(item));
console.log('unique :', unique, '| size:', size);
console.log('membership :', membership);
console.log('add again :', sizeAfterAdd, '| add returned the set:', returned === seen);
console.log('NaN and -0 :', oddValues.size, '| two equal objects:', objects.size);
console.log('order :', order);
console.log('union :', union, '| intersection:', intersection);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a Set drops the repeats', unique, ['Ikeja', 'Yaba', 'Lekki']);
test('size is the count of distinct values', size, 3);
test('has answers membership directly', membership, [true, false]);
test('adding something already present changes nothing, and returns the set', [sizeAfterAdd, returned === seen], [3, true]);
test('so add chains', chained, 2);
test('NaN deduplicates against itself and -0 folds into 0', oddValues.size, 2);
test('but two equal-looking objects are two distinct values', objects.size, 2);
test('the order is insertion order, not sorted', order, [3, 1, 2]);
test('union is a spread and intersection is a filter', [union, intersection], [['gari', 'rice', 'beans'], ['rice']]);
[...new Set(list)] is the shortest correct deduplication in the language, and it beats filter((v, i, a) => a.indexOf(v) === i) twice over: it is one pass rather than a scan per element, and it handles NaN, which indexOf cannot find at all.
The membership case is the one people under-use. set.has(x) is roughly constant time while array.includes(x) walks the array, so building a Set once and testing against it inside a loop turns quadratic work into linear — which is exactly what the intersection above does. Two cautions: identity again, so a Set of freshly parsed objects will never deduplicate no matter how identical they look; and a Set is not JSON, so JSON.stringify(set) is '{}' and you must spread it first.