Remove Duplicates from JavaScript Arrays
Removing duplicates depends on what “duplicate” means for your data. Primitive values, objects with unique IDs, and records compared by several properties need different strategies.
Primitive Values with Set Copy const values = [1, 2, 3, 2, 4, 3]; const unique = [...new Set(values)]; console.log(unique); // [1, 2, 3, 4] Keep the First Object for Each ID Copy const items = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice again' }, ]; const seen = new Set(); const unique = items.filter((item) => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); Keep the Last Object for Each ID A Map naturally overwrites earlier values for the same key: