JavaScript
Remove duplicate values from a JavaScript array
Wrap an array in a Set and spread it into a new array to remove repeated primitive values while keeping the order of their first appearance.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const values = ["blue", "red", "blue", "green"];
const unique = [...new Set(values)];
console.log(JSON.stringify(unique));How it works
Set stores each distinct value once. Iteration follows insertion order, so blue remains first even though it appears twice in the input. Spreading the set creates a separate array that you can map, sort, or serialize. The input array is unchanged.
Limits and mistakes
Objects are compared by identity, not by matching properties. Two separately created objects with the same ID remain different set entries. Decide whether object records should be deduplicated by ID before applying this recipe.
Check the result
The output should be ["blue","red","green"]. Test an empty array and repeated numbers as well. If you expect identical objects to collapse, use an ID-based Map instead.
Sources
Reference documentation for the behavior used in this guide: