我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在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数组中删除重复值

类似的问题:

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


当前回答

ES6/ES2015更新答案:使用Set和排列运算符(感谢le-m),单线解决方案为:

let uniqueItems = [...new Set(items)]

哪个会返回

[4, 5, 6, 3, 2, 23, 1]

其他回答

很多人已经提到使用。。。

[...new Set(arr)];

这是一个很好的解决方案,但我的首选是与.filter一起使用的解决方案。在我看来,filter是获取唯一值的更自然的方法。您可以有效地删除重复项,而从数组中删除元素正是过滤器的作用所在。它还允许您链接.map、.reduce和其他.filter调用。我设计了这个解决方案。。。

const unique = () => {
  let cache;  
  return (elem, index, array) => {
    if (!cache) cache = new Set(array);
    return cache.delete(elem);
  };
};

myArray.filter(unique());

需要注意的是,你需要一个结束,但我认为这是一个值得的权衡。就性能而言,它比我看到的使用.filter的其他解决方案更具性能,但比[…new Set(arr)]性能更差。

另请参阅我的github包

您也可以使用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.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);})();下面是解决这个问题的简单方法。。。

我知道这个问题已经解决了。。。但是没有人提到linq的javascript实现。然后就可以使用.dispect()方法了,这使得代码非常容易阅读。

var Linq = require('linq-es2015');
var distinctValues =  Linq.asEnumerable(testValues)
            .Select(x)
            .distinct()
            .toArray();

var测试值=[1,2,3,4,5,6,7,8,9,0,1,2,1];var distinctValues=可枚举.asEnumerable(测试值).dispect().toArray();console.log(distinctValues);<script src=“https://npmcdn.com/linq-es5/dist/linq.js“></script>