jQuery function to get all unique elements from an

2020-01-23 07:15发布

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

14条回答
别忘想泡老子
2楼-- · 2020-01-23 07:27

Plain JavaScript modern solution if you don't need IE support (Array.from is not supported in IE).

You can use combination of Set and Array.from.

const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];
const set = new Set(arr);
const uniqueArr = Array.from(set);

console.log(uniqueArr);

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.

const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];
const set = new Set(arr);
const uniqueArr = [...set];

console.log(uniqueArr);

查看更多
爷、活的狠高调
3楼-- · 2020-01-23 07:32

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]);
查看更多
做自己的国王
4楼-- · 2020-01-23 07:32

If you need to support IE 8 or earlier, you can use jQuery to accomplish this.

var a = [1,2,2,3,4,3,5];
var unique = $.grep(a, function (item, index) {
   return index === $.inArray(item, a);
});
查看更多
The star\"
5楼-- · 2020-01-23 07:33

Based on @kennebec's answer, but fixed for IE8 and below by using jQuery wrappers around the array to provide missing Array functions filter and indexOf:

$.makeArray() wrapper might not be absolutely needed, but you'll get odd results if you omit this wrapper and JSON.stringify the result otherwise.

var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];

// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){ 
    // note: 'index', not 'indexOf'
    return i == $(a).index(itm);
}));

// unique: [1, 5, 6, 4, 2, 3]
查看更多
Fickle 薄情
6楼-- · 2020-01-23 07:34

You can use a jQuery plugin called Array Utilities to get an array of unique items. It can be done like this:

var distinctArray = $.distinct([1, 2, 2, 3])

distinctArray = [1,2,3]

查看更多
唯我独甜
7楼-- · 2020-01-23 07:35

As of jquery 3.0 you can use $.uniqueSort(ARRAY)

Example

array = ["1","2","1","2"]
$.uniqueSort(array)
=> ["1", "2"]
查看更多
登录 后发表回答