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

其他回答

这是因为0在JavaScript中是一个错误的值。

如果数组的值为0或任何其他错误值,则此[i]将是错误的。

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
}

奇怪的是,这以前没有人提出过。。要按数组中的对象键(下面的id)删除重复项,可以执行以下操作:

const uniqArray = array.filter((obj, idx, arr) => (
  arr.findIndex((o) => o.id === obj.id) === idx
)) 

桩的另一个解决方案。

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

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

对于字符串数组:

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