JavaScriptFundamental (ES6), part 1
Remove duplicate objects by key (uniqBy) in JavaScript
97 uniq, uniqBy, and what Set counts as the same
easyDedupe a list two ways: uniq through a Set, and uniqBy(items, key) where the key is a property name or a function. Keep the first of each duplicate group. Then pin down exactly which values a Set treats as the same, because it is not what === or indexOf does.
Stuck? Three hints, smallest first
- 1.
[...new Set(items)]is the whole ofuniq, and it already keeps first-seen order. - 2. For
uniqBythe Set holds the keys, not the items, and a separate array collects the items you decided to keep. - 3. Two objects are only ever the same value if they are the same object. If you want to dedupe by contents, the key function has to produce a primitive.
const uniq = (items) => [...new Set(items)];
const uniqBy = (items, key) => {
const of = typeof key === 'function' ? key : (item) => item[key];
const seen = new Set();
const out = [];
for (const item of items) {
const k = of(item);
if (!seen.has(k)) {
seen.add(k);
out.push(item);
}
}
return out;
};
const payments = [
{ ref: 'PX-1', phone: '0803 111 2222', amount: 5000 },
{ ref: 'PX-2', phone: '08031112222', amount: 5000 },
{ ref: 'PX-3', phone: '0805 333 4444', amount: 1500 },
{ ref: 'PX-4', phone: '0803 111 2222', amount: 7000 },
];
const digitsOnly = (text) => [...text].filter((c) => c !== ' ').join('');
const refs = (list) => list.map((p) => p.ref);
const plain = uniq(['yaba', 'ikeja', 'yaba', 'lekki', 'ikeja']);
const nanCount = uniq([NaN, NaN, NaN]).length;
const indexOfNaN = [NaN].indexOf(NaN);
const zeroCount = uniq([0, -0]).length;
const looseCount = uniq(['1', 1]).length;
const objectCount = uniq([{ lga: 'Yaba' }, { lga: 'Yaba' }]).length;
const byPhone = refs(uniqBy(payments, 'phone'));
const byNormalised = refs(uniqBy(payments, (p) => digitsOnly(p.phone)));
const keptAmounts = uniqBy(payments, 'phone').map((p) => p.amount);
const byPair = refs(uniqBy(payments, (p) => `${digitsOnly(p.phone)}|${p.amount}`));
console.log('uniq :', plain);
console.log('NaN :', nanCount, '| indexOf says:', indexOfNaN);
console.log('by phone :', byPhone, '| normalised:', byNormalised);
console.log('by pair :', byPair);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('uniq keeps the first of each value, in order', plain, ['yaba', 'ikeja', 'lekki']);
test('a Set treats NaN as equal to itself, which indexOf never does', [nanCount, indexOfNaN], [1, -1]);
test('0 and -0 collapse, but a string and a number never do', [zeroCount, looseCount], [1, 2]);
test('two objects with identical fields are two different values', objectCount, 2);
test('uniqBy on a property dedupes on that property', byPhone, ['PX-1', 'PX-2', 'PX-3']);
test('it keeps the first of a group, so the later amount is the one dropped', keptAmounts, [5000, 5000, 1500]);
test('a key function normalises before comparing, which catches the real duplicate', byNormalised, ['PX-1', 'PX-3']);
test('a template-string key dedupes on two fields at once', byPair, ['PX-1', 'PX-3', 'PX-4']);
A Set compares with SameValueZero, which is === with one repair and one wart. The repair: NaN equals itself, so a list of NaNs dedupes to one, while indexOf — which uses strict equality — can never find a NaN at all. The wart: 0 and -0 are treated as the same value, which is right for counting and wrong if the sign carries meaning, such as a debit direction.
Everything else follows from objects comparing by identity. uniq on a list of records does nothing useful, because no two records are ever the same value unless they are the same object. That is why uniqBy exists, and why its key function must return a primitive: a key function returning an object leaves you exactly where you started.
Two things about the key. Building it from a template string is fine until a field contains your separator, which is how '0803|111' and '0803', '111' end up as one group; pick a separator the data cannot contain, or nest Maps. And normalising inside the key — stripping the spaces from a phone number here — is where the real duplicates get caught, because raw data is almost never duplicated in exactly the same shape.