Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function to get all unique elements from an array?

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.)

like image 965
Crashalot Avatar asked Mar 21 '11 17:03

Crashalot


People also ask

How do you make an array unique in jQuery?

The $. unique() method sorts an array of DOM elements and removes the duplicates. It returns the sorted array after removing the duplicates. This method is deprecated from jQuery version 3.0, and we can use jQuery.

What is grep function in jQuery?

grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.


2 Answers

You can use array.filter to return the first item of each distinct value-

var a = [ 1, 5, 1, 6, 4, 5, 2, 5, 4, 3, 1, 2, 6, 6, 3, 3, 2, 4 ];    var unique = a.filter(function(itm, i, a) {      return i == a.indexOf(itm);  });    console.log(unique);

If supporting IE8 and below is primary, don't use the unsupported filter method.

Otherwise,

if (!Array.prototype.filter) {     Array.prototype.filter = function(fun, scope) {         var T = this, A = [], i = 0, itm, L = T.length;         if (typeof fun == 'function') {             while(i < L) {                 if (i in T) {                     itm = T[i];                     if (fun.call(scope, itm, i, T)) A[A.length] = itm;                 }                 ++i;             }         }         return A;     } } 
like image 194
kennebec Avatar answered Sep 22 '22 06:09

kennebec


Just use this code as the basis of a simple JQuery plugin.

$.extend({     distinct : function(anArray) {        var result = [];        $.each(anArray, function(i,v){            if ($.inArray(v, result) == -1) result.push(v);        });        return result;     } }); 

Use as so:

$.distinct([0,1,2,2,3]); 
like image 39
js1568 Avatar answered Sep 25 '22 06:09

js1568