How to get unique values in an array

后端 未结 20 2248
情歌与酒
情歌与酒 2020-11-22 14:02

How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java\'s hashmap in JavaScript?

I am going

20条回答
  •  误落风尘
    2020-11-22 14:34

    If you want to leave the original array intact,

    you need a second array to contain the uniqe elements of the first-

    Most browsers have Array.prototype.filter:

    var unique= array1.filter(function(itm, i){
        return array1.indexOf(itm)== i; 
        // returns true for only the first instance of itm
    });
    
    
    //if you need a 'shim':
    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

提交回复
热议问题