我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在Stack Overflow上找到了另一个脚本,看起来几乎与它完全一样,但它不会失败。

所以为了帮助我学习,有人能帮我确定原型脚本哪里出错吗?

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

重复问题的更多答案:

从JS数组中删除重复值

类似的问题:

获取数组中的所有非唯一值(即:重复/多次出现)


当前回答

(函数(){“使用严格”;Array.prototype.unique=函数unique(){var self=this;返回自滤波器(函数(a){var=this;//console.log(那个);回来那是什么?[a]=真:假;}, {});}var sampleArray=[0,1,2,3,4,5,6,7,8,9,0,1,4,2,6,4,8,9];var distinctArray=sampleArray.unique();console.log(distinctArray);})();下面是解决这个问题的简单方法。。。

其他回答

使用Set删除重复项。

具有重复项的阵列

const withDuplicates = [2, 2, 5, 5, 1, 1, 2, 2, 3, 3];

使用Set获取不重复的新数组

const withoutDuplicates = Array.from(new Set(withDuplicates));

较短版本

const withoutDuplicates = [...new Set(withDuplicates)];

结果:[2,5,1,3]

您也可以使用underscore.js。

控制台日志(_.uniq([1,2,1,3,1,4]));<script src=“http://underscorejs.org/underscore-min.js“></script>

其将返回:

[1, 2, 3, 4]

如果您使用的是Prototype框架,则无需执行“for”循环,您可以使用http://prototypejs.org/doc/latest/language/Array/prototype/uniq/这样地:

var a = Array.uniq();  

这将产生一个没有重复的重复数组。我在搜索一个方法来计数不同的数组记录时遇到了您的问题,所以在uniq()之后,我使用了size(),得到了一个简单的结果。对不起,如果我打错了

edit:如果您想转义未定义的记录,您可能需要在前面添加compact(),如下所示:

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

桩的另一个解决方案。

我最近需要使一个排序列表唯一,我使用过滤器来跟踪对象中的前一项,如下所示:

uniqueArray = sortedArray.filter(function(e) { 
    if(e==this.last) 
      return false; 
    this.last=e; return true;  
  },{last:null});