How can I remove duplicates from an array while keeping its order?
Quick answer
In JavaScript, convert the array to a Set and spread it back into an array: const unique = [...new Set(values)];. A Set keeps values in insertion order, so the first occurrence stays in its original position. For objects, it removes a repeated reference to the same object, but not separate objects that merely have matching properties. [S1]
The question, the details, the next step.
A practical checklist
Decide whether duplicates mean equal values, the same object reference, or a matching object field.
Use
[...new Set(values)]when Set's value-equality rules match your requirement.Test an input with repeats in different positions and verify first-occurrence order.
For objects, test a repeated reference and separate objects with matching properties.
A few more useful answers
Does this change the original array?
No. [...new Set(values)] creates a new array; it does not remove entries from values.
Will two objects with identical properties be deduplicated?
Not if they are separate object instances. Set recognizes the same object reference, not matching object contents. [S1]
Does the result keep the first or last occurrence?
It keeps each value at its first position in the input's iteration order. [S1]
Sources
References used for this guide.
- [S1] Set — JavaScript | MDN developer.mozilla.org · Checked
