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条回答
Anthone
2楼-- · 2020-01-23 07:51

If anyone is using knockoutjs try:

ko.utils.arrayGetDistinctValues()

BTW have look at all ko.utils.array* utilities.

查看更多
萌系小妹纸
3楼-- · 2020-01-23 07:54

this is js1568's solution, modified to work on a generic array of objects, like:

 var genericObject=[
        {genProp:'this is a string',randomInt:10,isBoolean:false},
        {genProp:'this is another string',randomInt:20,isBoolean:false},
        {genProp:'this is a string',randomInt:10,isBoolean:true},
        {genProp:'this is another string',randomInt:30,isBoolean:false},
        {genProp:'this is a string',randomInt:40,isBoolean:true},
        {genProp:'i like strings',randomInt:60,isBoolean:true},
        {genProp:'this is a string',randomInt:70,isBoolean:true},
        {genProp:'this string is unique',randomInt:50,isBoolean:true},
        {genProp:'this is a string',randomInt:50,isBoolean:false},
        {genProp:'i like strings',randomInt:70,isBoolean:false}
    ]

It accepts one more parameter called propertyName, guess! :)

  $.extend({
        distinctObj:function(obj,propertyName) {
            var result = [];
            $.each(obj,function(i,v){
                var prop=eval("v."+propertyName);
                if ($.inArray(prop, result) == -1) result.push(prop);
            });
            return result;
        }
    });

so, if you need to extract a list of unique values for a given property, for example the values used for randomInt property, use this:

$.distinctObj(genericObject,'genProp');

it returns an array like this:

["this is a string", "this is another string", "i like strings", "this string is unique"] 
查看更多
登录 后发表回答