Remove duplicate values from an array
Quick Answer
Spreading a Set over an array is the simplest way to remove duplicates from a flat array in JavaScript. For arrays of objects, use a Map keyed by a unique property.
1const unique = (arr) => [...new Set(arr)];
2
3// Or for array of objects
4const uniqueBy = (arr, key) => {
5 return [...new Map(arr.map(item => [item[key], item])).values()];
6};Removing duplicates from arrays is a common task in JavaScript. Using the Set data structure provides the most efficient way to get unique values. For arrays of objects, we use Map to deduplicate based on a specific property.
Yes. Set iterates values in insertion order, so the first occurrence of each value is kept.
Stringify the relevant keys into a composite string and use that as the Map key.
O(n) — each element is visited once when building the Set.
This free javascript code snippet for get unique array values is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement get unique array values quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.