Removing duplicate elements
suggest changeThe concise modern approach is to construct a Set, whose values are unique, and spread it back into an array:
const uniqueValues = [...new Set(['a', 1, 'a', 2, '1', 1])];
// ['a', 1, 2, '1']
For custom equality—such as uniqueness by an object's id—use a Map keyed by the relevant property:
const records = [{ id: 1, name: 'first' }, { id: 1, name: 'updated' }];
const uniqueById = [...new Map(records.map(record => [record.id, record])).values()];
// [{ id: 1, name: 'updated' }] — the later record replaces the earlier one
Set compares objects by identity, not by their contents, so two distinct object instances are not duplicates even when their properties are equal.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents