How to get unique values in an array

2019-01-01 02:26发布

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 to be using JavaScript and jQuery only. No additional libraries can be used.

28条回答
几人难应
2楼-- · 2019-01-01 02:30

ES6 way:

const uniq = (arr) => (arr.filter((item, index, arry) => (arry.indexOf(item) === index)));
查看更多
泛滥B
3楼-- · 2019-01-01 02:31

One Liner, Pure JavaScript

With ES6 syntax

list = list.filter((x, i, a) => a.indexOf(x) == i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

enter image description here

With ES5 syntax

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) == i; 
});

Browser Compatibility: IE9+

查看更多
唯独是你
4楼-- · 2019-01-01 02:32

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

Array.prototype.contains = function(v) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] === v) return true;
    }
    return false;
};

Array.prototype.unique = function() {
    var arr = [];
    for(var i = 0; i < this.length; i++) {
        if(!arr.includes(this[i])) {
            arr.push(this[i]);
        }
    }
    return arr; 
}

You can then do:

var duplicates = [1,3,4,2,1,2,3,8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

查看更多
牵手、夕阳
5楼-- · 2019-01-01 02:32

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<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
 Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
        if(!i || typeof i!= 'number') i= 0;
        var L= this.length;
        while(i<L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }
查看更多
人间绝色
6楼-- · 2019-01-01 02:32

Another thought of this question. Here is what I did to achieve this with fewer code.

var distinctMap = {};
var testArray = ['John', 'John', 'Jason', 'Jason'];
for (var i = 0; i < testArray.length; i++) {
  var value = testArray[i];
  distinctMap[value] = '';
};
var unique_values = Object.keys(distinctMap);
查看更多
回忆,回不去的记忆
7楼-- · 2019-01-01 02:32
function findUniques(arr){
  let uniques = []
  arr.forEach(n => {
    if(!uniques.includes(n)){
      uniques.push(n)
    }       
  })
  return uniques
}

let arr = ["3", "3", "4", "4", "4", "5", "7", "9", "b", "d", "e", "f", "h", "q", "r", "t", "t"]

findUniques(arr)
// ["3", "4", "5", "7", "9", "b", "d", "e", "f", "h", "q", "r", "t"]
查看更多
登录 后发表回答