我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在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 = function() {
  return this.filter(function(value, index, array) {
    return array.indexOf(value, index + 1) < 0;
  });
};

或在CoffeeScript中:

Array.prototype.unique = ->
  this.filter( (value, index, array) ->
    array.indexOf(value, index + 1) < 0
  )

其他回答

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
}

这个解决方案应该非常快,并且在很多情况下都有效。

将索引数组项转换为对象键使用Object.keys函数var indexArray=[“hi”,“welcome”,“欢迎”,1,-9];var keyArray={};indexArray.forEach(函数(项){keyArray[item]=null;});var uniqueArray=对象.keys(keyArray);

[...new Set(duplicates)]

这是从MDN Web文档中引用的最简单的一个。

const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)]) // [2, 3, 4, 5, 6, 7, 32]

使用ES6新设置

变量数组=[3,7,5,3,2,5,2,7];var unique_array=[…新集合(数组)];console.log(unique_array);//输出=[3,7,5,2]

使用For循环

变量数组=[3,7,5,3,2,5,2,7];for(var i=0;i<array.length;i++){for(变量j=i+1;j<array.length;j++){如果(array[i]===array[j]){阵列.拼接(j,1);}}}console.log(数组);//输出=[3,7,5,2]

你根本不需要.indexOf();你可以这样做O(n):

function SelectDistinct(array) {
    const seenIt = new Set();

    return array.filter(function (val) {
        if (seenIt.has(val)) { 
            return false;
        }

        seenIt.add(val);

        return true;
    });
}

var hasDuplicates = [1,2,3,4,5,5,6,7,7];
console.log(SelectDistinct(hasDuplicates)) //[1,2,3,4,5,6,7]

如果不想使用.filter():

function SelectDistinct(array) {
    const seenIt = new Set();
    const distinct = [];

    for (let i = 0; i < array.length; i++) {
        const value = array[i];

        if (!seenIt.has(value)) {
            seenIt.add(value);
            distinct.push(value);
        }
    }
    
    return distinct; 
    /* you could also drop the 'distinct' array and return 'Array.from(seenIt)', which converts the set object to an array */
}