How to get unique values in an array

后端 未结 20 2233
情歌与酒
情歌与酒 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:51

    Majority of the solutions above have a high run time complexity.

    Here is the solution that uses reduce and can do the job in O(n) time.

    Array.prototype.unique = Array.prototype.unique || function() {
            var arr = [];
    	this.reduce(function (hash, num) {
    		if(typeof hash[num] === 'undefined') {
    			hash[num] = 1; 
    			arr.push(num);
    		}
    		return hash;
    	}, {});
    	return arr;
    }
        
    var myArr = [3,1,2,3,3,3];
    console.log(myArr.unique()); //[3,1,2];

    Note:

    This solution is not dependent on reduce. The idea is to create an object map and push unique ones into the array.

提交回复
热议问题