jQuery.unique lets you get unique elements of an array, but the docs say the function is mostly for internal use and only operates on DOM elements. Another SO response said the unique()
function worked on numbers, but that this use case is not necessarily future proof because it's not explicitly stated in the docs.
Given this, is there a "standard" jQuery function for accessing only the unique values — specifically, primitives like integers — in an array? (Obviously, we can construct a loop with the each()
function, but we are new to jQuery and would like to know if there is a dedicated jQuery function for this.)
Plain JavaScript modern solution if you don't need IE support (
Array.from
is not supported in IE).You can use combination of
Set
andArray.from
.The
Set
object lets you store unique values of any type, whether primitive values or object references.The
Array.from()
method creates a new Array instance from an array-like or iterable object.Also
Array.from()
can be replaced with spread operator.Just use this code as the basis of a simple JQuery plugin.
Use as so:
If you need to support IE 8 or earlier, you can use jQuery to accomplish this.
Based on @kennebec's answer, but fixed for IE8 and below by using jQuery wrappers around the array to provide missing Array functions
filter
andindexOf
:$.makeArray() wrapper might not be absolutely needed, but you'll get odd results if you omit this wrapper and JSON.stringify the result otherwise.
You can use a jQuery plugin called Array Utilities to get an array of unique items. It can be done like this:
distinctArray = [1,2,3]
As of jquery 3.0 you can use
$.uniqueSort(ARRAY)
Example