Understanding the jQuery $.unique() Method
The jQuery $.unique() method is a built-in utility
function designed specifically to remove duplicate DOM elements from an
array. This article explains the primary purpose of the
$.unique() method, how it operates under the hood, critical
limitations to be aware of, and its modern replacement in newer versions
of jQuery.
Primary Purpose of $.unique()
The $.unique() method sorts an array of DOM elements in
place and removes all duplicate entries. The resulting array contains
each element only once, ordered according to the document order (the
order in which the elements appear in the HTML source).
// Example: Combining two element selections that share nodes
var listItems1 = $("ul.primary li").get();
var listItems2 = $("li.active").get();
// Merge the arrays
var combined = listItems1.concat(listItems2);
// Remove duplicates
var uniqueList = $.unique(combined);Important Limitation: DOM Elements Only
A common misconception is that $.unique() works on
standard JavaScript arrays containing primitive types such as numbers or
strings. It does not.
The method relies on internal object identity comparisons
specifically tailored for browser DOM nodes. If you pass an array of
strings or numbers into $.unique(), it will either return
unexpected results, fail silently, or not remove duplicates at all. For
general array deduplication, modern JavaScript features like
Set (e.g., [...new Set(array)]) or
Array.prototype.filter() should be used instead.
Mutation of the Original Array
The $.unique() method operates directly on the array
passed to it. It does not create a clone; it modifies the original array
in place while also returning a reference to that modified array.
Modern Replacement: $.uniqueSort()
Starting with jQuery 3.0, $.unique() was deprecated and
renamed to $.uniqueSort().
The jQuery team introduced this change because the original name did
not clearly communicate that the elements were also being reordered into
document order. The behavior remains identical to
$.unique(), but $.uniqueSort() should be used
in all modern projects to ensure future compatibility.