Removing duplicate elements

suggest change

The 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents