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

类似的问题:

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


当前回答

设ar=[1,2,3,4,5,6,1,2,4,2,1];let unique=ar.filter((值,索引)=>{return ar.indexOf(value)==索引;});console.log(唯一);

其他回答

您也可以使用sugar.js:

[1,2,2,3,1].unique() // => [1,2,3]

[{id:5, name:"Jay"}, {id:6, name:"Jay"}, {id: 5, name:"Jay"}].unique('id') 
  // => [{id:5, name:"Jay"}, {id:6, name:"Jay"}]

我有一个解决方案,它使用es6 reduce和find数组助手方法来删除重复项。

设数=[2,2,3,3,5,6,6];const removeDups=数组=>{return array.reduce((acc,inc)=>{如果(!acc.find(i=>i===inc)){acc.push(包括);}返回acc;}, []);}console.log(removeDups(数字));///[2,3,5,6]

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

[...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包

使用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]

对于字符串数组:

function removeDuplicatesFromArray(arr) {
  const unique = {};
  arr.forEach((word) => {
    unique[word] = 1; // it doesn't really matter what goes here
  });
  return Object.keys(unique);
}