Get all the unique values of JavaScript array (remove duplicates)

This translation from: the Get All A UNIQUE values in JavaScript Array (the Remove Duplicates)

I have an array of numbers that I need to make sure are unique. I need to identify a unique array of numbers. I found the code snippet below on the internet and it works great until the array has a zero in it. I found the following code fragment on the Internet, and contains zero before it will work properly in the array. Found the I the this OTHER Script here Wallpaper Almost ON SO that looks exactly like IT, But IT does not Fail. I found on the SO another script , looks almost exactly the same, but it will not fail.

So for the sake of helping me learn , can someone help me determine where the prototype script is going wrong? So to help me learn, someone can help me determine prototype script what's the problem?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push (e)};
 return a;
}

More answers from duplicate question: more answers from repeated questions:

Similar question: Similar question:


#1st Floor

Reference: https://stackoom.com/question/8E0X/ all unique value acquisition JavaScript array - remove duplicates


#2nd Floor

CAN Also use by You Underscore.js . You can also use Underscore.js .

 console.log(_.uniq([1, 2, 1, 3, 1, 4])); 
 <script src="http://underscorejs.org/underscore-min.js"></script> 

which will return: it returns:

[1, 2, 3, 4]

#3rd floor

I have since found a nice method that uses jQuery since then, I found a good way of using jQuery

arr = $.grep(arr, function(v, k){
    return $.inArray(v ,arr) === k;
});

Note: This code WAS pulled from Paul Irish's Duck punching POST - the I, Ltd Forgot to give at Credit: P Note: This code is from Paul Irish duck punch posts extract of - I forgot to give you the gratitude: P


#4th floor

Prototype the this getUniqueIS not the Totally correct, Because IF i have have like Array A: ["1",1,2,3,4,1,"foo"]IT by Will return ["1","2","3","4"]and "1"IS and String 1IS A Integer; this prototype getUniqueis not entirely correct, because if I have an array Array is similar: ["1",1,2,3,4,1,"foo"]it returns ["1","2","3","4"]and "1"a string , 1is an integer; they are different. they are not the same.

Here is a correct solution: This is the right solution:

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });

using: Use:

var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();

Above by Will Produce at The ["1",2,3,4,1,"foo"]. Above will produce ["1",2,3,4,1,"foo"].


#5th Floor

The From Shamasis Bhattacharya 'Blog S (O (2n) Time Complexity): from Shamasis Bhattacharya the blog (O (2n) time complexity):

Array.prototype.unique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i+=1) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
    return r;
};

The From Paul Irish 'S Blog : Improvement ON JQuery .unique(): from Paul Irish blog is : JQuery .unique()improvements:

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

// in use..
var arr = ['first',7,true,2,7,true,'last','last'];
$.unique(arr); // ["first", 7, true, 2, "last"]

var arr = [1,2,3,4,5,4,3,2,1];
$.unique(arr); // [1, 2, 3, 4, 5]

#6th floor

With JavaScript 1.6 / ECMAScript 5 you CAN use at The Native filterMethod, of AN Array in at The following Way to GET AN Array with UNIQUE values: the use of JavaScript 1.6 / ECMAScript 5, the machine that you can use Array by way of filtermethods to obtain a unique value array:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

Native Method, at The filterby Will at The Loop Array and through the Leave Those entries It only GIVEN that Pass at The callback function onlyUnique. Native method filteriterates through the array, retaining only those given to the callback function onlyUnique.

onlyUniquechecks, if the given value is the first occurring. onlyUniqueCheck whether a given value is the first occurrence. If not, it must be a duplicate and will not be copied. If not, it must be repeated and will not be copied.

This solution works without any extra library like jQuery or prototype.js. This solution does not require any additional libraries (such as jQuery or prototype.js) to work.

It works for arrays with mixed value types too. It is also applicable to a mixed array value types.

The For Old the Browsers (<IE9), that do not Support at The Native Methods filterand indexOfyou CAN the Find Work arounds in at The MDN Documentation for filter and indexOf . For older browsers (<IE9), does not support the method of native filterand indexOfyou can find MDN document modifications filter and the indexOf .

You want to the Keep at The IF Last occurrence of A value, the replace the Simple indexOfby lastIndexOf. If you want to keep the value of the last occurrence, simply indexOfreplaced lastIndexOf.

With ES6 it could be shorten to this : Use ES6 can be simplified to:

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

To Thanks Camilo Martin for hint in the Comment. Thank Camilo Martin 's comments prompt.

Native Object A has for ES6 Setto Store UNIQUE values. For ES6 a native object Setis used to store a unique value. To get an array with unique values you could do now this: To get an array with unique values, you can now do the following:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']

Of constructor of The SetTakes AN Iterable Object, like the Array, and Spread The operator ...Transform The SET Back INTO AN Array. SetConstructor using object (e.g. Array) an iterative and distribute operator ...to set converted back Array. To Thanks Lukas Liese for hint in the Comment. Thank Lukas Liese comments prompt.

Original articles published 0 · won praise 136 · views 830 000 +

Guess you like

Origin blog.csdn.net/xfxf996/article/details/105245147