我有一个非常简单的JavaScript数组,可能包含也可能不包含重复项。

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

我需要删除重复项并将唯一值放入新数组。

我可以指出我尝试过的所有代码,但我认为它们没有用,因为它们不起作用。我也接受jQuery解决方案。

类似的问题:

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


当前回答

顶级答案的复杂度为O(n²),但这可以通过使用对象作为哈希来实现,只需O(n):

function getDistinctArray(arr) {
    var dups = {};
    return arr.filter(function(el) {
        var hash = el.valueOf();
        var isDup = dups[hash];
        dups[hash] = true;
        return !isDup;
    });
}

这将适用于字符串、数字和日期。如果您的数组包含对象,则上述解决方案将不起作用,因为当强制为字符串时,它们都将具有“[objectObject]”(或类似的值),这不适合作为查找值。通过在对象本身上设置标志,可以获得对象的O(n)实现:

function getDistinctObjArray(arr) {
    var distinctArr = arr.filter(function(el) {
        var isDup = el.inArray;
        el.inArray = true;
        return !isDup;
    });
    distinctArr.forEach(function(el) {
        delete el.inArray;
    });
    return distinctArr;
}

2019年编辑:JavaScript的现代版本使这个问题更容易解决。无论数组中是否包含对象、字符串、数字或任何其他类型,都可以使用Set。

function getDistinctArray(arr) {
    return [...new Set(arr)];
}

实现如此简单,不再需要定义函数。

其他回答

这可能是从阵列中永久删除重复项的最快方法之一比这里的大多数功能快10倍。&狩猎速度快78倍

function toUnique(a,b,c){               //array,placeholder,placeholder
 b=a.length;while(c=--b)while(c--)a[b]!==a[c]||a.splice(c,1)
}

测试:http://jsperf.com/wgu演示:http://jsfiddle.net/46S7g/更多信息:https://stackoverflow.com/a/25082874/2450730

如果你看不懂上面的代码,请看一本javascript书,或者这里有一些关于较短代码的解释。https://stackoverflow.com/a/21353032/2450730

复杂度为O(n)的Vanilla JS解决方案(对于这个问题最快)。如果需要,修改hashFunction以区分对象(例如1和“1”)。第一种解决方案避免了隐藏循环(在Array提供的函数中常见)。

var dedupe = function(a) 
{
    var hash={},ret=[];
    var hashFunction = function(v) { return ""+v; };
    var collect = function(h)
    {
        if(hash.hasOwnProperty(hashFunction(h)) == false) // O(1)
        {
            hash[hashFunction(h)]=1;
            ret.push(h); // should be O(1) for Arrays
            return;
        }
    };

    for(var i=0; i<a.length; i++) // this is a loop: O(n)
        collect(a[i]);
    //OR: a.forEach(collect); // this is a loop: O(n)

    return ret;
}

var dedupe = function(a) 
{
    var hash={};
    var isdupe = function(h)
    {
        if(hash.hasOwnProperty(h) == false) // O(1)
        {
            hash[h]=1;
            return true;
        }

        return false;
    };

    return a.filter(isdupe); // this is a loop: O(n)
}

aLinks是一个简单的JavaScript数组对象。如果在索引显示已删除重复记录的元素之前存在任何元素。我重复以取消所有重复。一个通道阵列取消更多记录。

var srt_ = 0;
var pos_ = 0;
do {
    var srt_ = 0;
    for (var i in aLinks) {
        pos_ = aLinks.indexOf(aLinks[i].valueOf(), 0);
        if (pos_ < i) {
            delete aLinks[i];
            srt_++;
        }
    }
} while (srt_ != 0);

另一种不用编写太多代码就可以做到这一点的方法是使用ES5 Object.keys-method:

var arrayWithDuplicates = ['a','b','c','d','a','c'],
    deduper = {};
arrayWithDuplicates.forEach(function (item) {
    deduper[item] = null;
});
var dedupedArray = Object.keys(deduper); // ["a", "b", "c", "d"]

在函数中提取

function removeDuplicates (arr) {
    var deduper = {}
    arr.forEach(function (item) {
        deduper[item] = null;
    });
    return Object.keys(deduper);
}

这里非常简单,可以在任何地方(甚至在PhotoshopScript中)理解和工作代码。检查一下!

var peoplenames = new Array("Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl");

peoplenames = unique(peoplenames);
alert(peoplenames);

function unique(array){
    var len = array.length;
    for(var i = 0; i < len; i++) for(var j = i + 1; j < len; j++) 
        if(array[j] == array[i]){
            array.splice(j,1);
            j--;
            len--;
        }
    return array;
}

//*result* peoplenames == ["Mike","Matt","Nancy","Adam","Jenny","Carl"]