IT박스

배열에서 모든 고유 요소를 가져 오는 jQuery 함수?

itboxs 2020. 10. 28. 07:54
반응형

배열에서 모든 고유 요소를 가져 오는 jQuery 함수?


jQuery.unique를 사용하면 배열의 고유 요소를 얻을 수 있지만 문서에서는 함수가 대부분 내부 용이며 DOM 요소에서만 작동한다고 말합니다. 또 다른 SO 응답은 unique()함수가 숫자에 대해 작동했지만이 사용 사례가 문서에 명시 적으로 명시되어 있지 않기 때문에 반드시 미래의 증거는 아니라고 말했습니다.

이 점을 감안할 때 배열에서 고유 한 값, 특히 정수와 같은 프리미티브에만 액세스하는 "표준"jQuery 함수가 있습니까? (분명히 우리는 each()함수 로 루프를 구성 할 수 있지만 jQuery를 처음 접했고이를위한 전용 jQuery 함수가 있는지 알고 싶습니다.)


array.filter각 고유 값의 첫 번째 항목을 반환하는 데 사용할 수 있습니다 .

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

IE8 이하 지원이 기본 인 경우 지원되지 않는 filter방법을 사용하지 마십시오 .

그렇지 않으면,

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;
    }
}

이 코드를 간단한 JQuery 플러그인의 기초로 사용하십시오.

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

그렇게 사용 :

$.distinct([0,1,2,2,3]);

@ 케네 벡의 대답을 기반으로하지만, IE8과 아래에 배열 함수 실종 제공하기 위해 배열 주위의 jQuery 래퍼를 사용하여 고정 filterindexOf:

$ .makeArray () 래퍼가 절대적으로 필요하지 않을 수도 있지만,이 래퍼를 생략하고 그렇지 않으면 결과를 JSON.stringify하면 이상한 결과를 얻을 수 있습니다.

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]

원하는 작업을 수행 하는 방법을 제공하는 underscore.js를 사용 합니다uniq .


    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]

그리고 dom 요소의 경우 여기에 예제가 필요하지 않습니다. 이미 알고 있기 때문입니다!

다음은 라이브 예제의 jsfiddle 링크입니다. http://jsfiddle.net/3BtMc/4/


배열을 살펴보고 항목을 발견하면 해시로 항목을 푸시합니다. 각각의 새 요소에 대한 해시를 상호 참조합니다.

이것은 원시 (문자열, 숫자, null, 정의되지 않음, NaN)와 동일한 것으로 직렬화되는 몇 가지 객체 (함수, 문자열, 날짜, 콘텐츠에 따라 배열 일 수 있음)에 대해서만 제대로 작동합니다. 이것의 해시는 모두 같은 것으로 직렬화 될 때 충돌합니다. 예 : "[object Object]"

Array.prototype.distinct = function(){
   var map = {}, out = [];

   for(var i=0, l=this.length; i<l; i++){
      if(map[this[i]]){ continue; }

      out.push(this[i]);
      map[this[i]] = 1;
   }

   return out;
}

jQuery.unique를 사용할 수없는 이유도 없습니다. 내가 싫어하는 유일한 점은 배열의 순서를 파괴한다는 것입니다. 관심이있는 경우 정확한 코드는 다음과 같습니다.

Sizzle.uniqueSort = function(results){
    if ( sortOrder ) {
        hasDuplicate = baseHasDuplicate;
        results.sort(sortOrder);

        if ( hasDuplicate ) {
            for ( var i = 1; i < results.length; i++ ) {
                if ( results[i] === results[i-1] ) {
                    results.splice(i--, 1);
                }
            }
        }
    }

    return results;
};

Paul Irish에는 모든 유형의 고유 한 요소를 반환하도록 jQuery의 메서드를 수정 하는 " Duck Punching "메서드 (예제 2 참조)가 있습니다 $.unique().

(function($){
    var _old = $.unique;
    $.unique = function(arr){
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

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"] 

function array_unique(array) {
    var unique = [];
    for ( var i = 0 ; i < array.length ; ++i ) {
        if ( unique.indexOf(array[i]) == -1 )
            unique.push(array[i]);
    }
    return unique;
}

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


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]


If anyone is using knockoutjs try:

ko.utils.arrayGetDistinctValues()

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


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

Example

array = ["1","2","1","2"]
$.uniqueSort(array)
=> ["1", "2"]

참고URL : https://stackoverflow.com/questions/5381621/jquery-function-to-get-all-unique-elements-from-an-array

반응형