JavaScript Snippet

Get Unique Items from an Array

Difficulty: Easy

Deduping an array sounds trivial until objects, NaN, and case-insensitive strings show up. This snippet walks from the one-liner everyone reaches for first, to a key-projecting variant that handles object identity, to the gotcha around NaN that catches even seasoned engineers. Pick the version that matches your data shape and keep the rest as reference.

Code Snippets
/

Get Unique Items from an Array

Get Unique Items from an Array

Deduping an array sounds trivial until objects, NaN, and case-insensitive strings show up. This snippet walks from the one-liner everyone reaches for first, to a key-projecting variant that handles object identity, to the gotcha around NaN that catches even seasoned engineers. Pick the version that matches your data shape and keep the rest as reference.

JavaScript
Easy
3 snippets
arrays
utility
set
code-template

468 views

12

Spreading an array into a Set and back into an array is the canonical JavaScript dedupe. Set uses the SameValueZero algorithm for membership, so it correctly treats NaN as equal to itself (unlike ===). It also preserves insertion order, which means the first occurrence of each value wins. Time complexity is O(n) average, but only for primitives. The next accordion shows why this breaks for objects.