我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在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);})();下面是解决这个问题的简单方法。。。

其他回答

你根本不需要.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 */
}

我们可以使用ES6集合来实现这一点:

var duplicatesArray=[1,2,3,4,5,1,1,2,4,4];var uniqueArray=[…new Set(duplicatesArray)];console.log(uniqueArray);//[1,2,3,4,5]

这个不是纯的,它会修改数组,但这是最快的。如果你的速度更快,请写下评论;)

http://jsperf.com/unique-array-webdeb

Array.prototype.uniq = function(){
    for(var i = 0, l = this.length; i < l; ++i){
        var item = this[i];
        var duplicateIdx = this.indexOf(item, i + 1);
        while(duplicateIdx != -1) {
            this.splice(duplicateIdx, 1);
            duplicateIdx = this.indexOf(item, duplicateIdx);
            l--;
        }
    }

    return this;
}

[
 "",2,4,"A","abc",
 "",2,4,"A","abc",
 "",2,4,"A","abc",
 "",2,4,"A","abc",
 "",2,4,"A","abc",
 "",2,4,"A","abc",
 "",2,4,"A","abc",
 "",2,4,"A","abc"
].uniq() //  ["",2,4,"A","abc"]

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

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

永远记住,内置方法易于使用。但请记住,它们具有复杂性。

基本逻辑是最好的。没有隐藏的复杂性。

let list = [1, 1, 2, 100, 2] // your array
let check = {}
list = list.filter(item => {
    if(!check[item]) {
        check[item] = true
        return true;
    }
})

或使用,如果您需要将来遍历检查项(但会浪费内存),则使用check=[]