What Elements Does jQuery uniqueSort Support?

The jQuery.uniqueSort() method operates exclusively on arrays of DOM elements, sorting the elements in document order and removing duplicates in place. This article explains the exact types of elements supported by $.uniqueSort(), why primitive data types are not compatible, and how to properly implement the method in your JavaScript code.

Supported Elements: Native DOM Nodes

The jQuery.uniqueSort() function (formerly known as jQuery.unique() prior to jQuery 3.0) is designed solely to work with arrays containing native DOM elements. These include:

  • Standard HTML elements (<div>, <p>, <span>, etc.)
  • XML elements within an XML document
  • The document and window objects, where applicable as node references

When passed an array of DOM elements, $.uniqueSort() modifies the array in place. It performs two specific tasks:

  1. Document Order Sorting: It arranges the elements based on where they appear within the DOM tree from top to bottom.
  2. Deduplication: It removes redundant references to the exact same DOM node so that each element appears only once in the final array.
// Example of valid usage with DOM elements
const elem1 = document.getElementById("first");
const elem2 = document.getElementById("second");

const domArray = [elem2, elem1, elem2];
jQuery.uniqueSort(domArray);

// Result: domArray is now sorted in document order with duplicates removed: [elem1, elem2]

Unsupported Elements: Primitives and Plain Objects

A common misconception is that $.uniqueSort() can be used as a generic utility to remove duplicate strings, numbers, or custom JavaScript objects. It does not work on these types.

The method relies internally on DOM-specific comparison algorithms, such as compareDocumentPosition or internal node indices, to determine order and uniqueness. Passing primitives or plain objects leads to unreliable behavior:

  • Strings and Numbers: The sorting algorithm fails because primitive values lack DOM hierarchy properties. In modern versions of jQuery, attempting to use non-element values can result in errors or an improperly sorted array.
  • Plain JavaScript Objects: Custom objects (e.g., { id: 1 }) cannot be sorted by document order and are not recognized as valid nodes.

Alternatives for Non-DOM Elements

If you need to sort and deduplicate primitive values like numbers or strings, use native modern JavaScript rather than jQuery:

// Deduplicate primitives using a Set
const numbers = [3, 1, 2, 3, 1];
const uniqueNumbers = [...new Set(numbers)].sort((a, b) => a - b);
// Result: [1, 2, 3]

To summarize, jQuery.uniqueSort() is strictly an internal-style utility for cleaning up arrays of native DOM nodes by document position and reference identity.