我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。

我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。

类似的问题:

获取JavaScript数组中所有唯一的值(删除重复值)


当前回答

下面是使用sort()和JSON.stringify()实现的一个

https://gist.github.com/korczis/7598657

function removeDuplicates(vals) {
    var res = [];
    var tmp = vals.sort();

    for (var i = 0; i < tmp.length; i++) {
        res.push(tmp[i]);
                    while (JSON.stringify(tmp[i]) == JSON.stringify(tmp[i + 1])) {
            i++;
        }
    }

    return res;
}
console.log(removeDuplicates([1,2,3,4,5,4,3,3,2,1,]));

其他回答

var isUnique = true;      
for (var i= 0; i< targetItems.length; i++) {
        var itemValue = $(targetItems[i]).val();
        if (targetListValues.indexOf(itemValue) >= 0) {
          isUnique = false;
           break;
        }
      targetListValues.push(itemValue);
        if (!isUnique) {
          //raise any error msg
          return false;
        }
      }

您可以对数组进行排序,然后遍历它,然后查看下一个(或上一个)索引是否与当前索引相同。假设你的排序算法是好的,这个应该小于O(n2):

const findDuplicates = (arr) => { let sorted_arr = arr.slice().sort(); // You can define the comparing function here. // JS by default uses a crappy string compare. // (we use slice to clone the array so the // original array won't be modified) let results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results; } let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7]; console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);

在这种情况下,如果你要返回一个重复的函数。这是为类似类型的情况。

参考:https://stackoverflow.com/a/57532964/8119511

//find duplicates: //sort, then reduce - concat values equal previous element, skip others //input var a = [1, 2, 3, 1, 2, 1, 2] //short version: var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, []) console.log(duplicates); //[1, 1, 2, 2] //readable version: var duplicates = a.sort().reduce((output, element, index, input) => { if ((index > 0) && (element === input[index - 1])) return output.concat(element) return output }, []) console.log(duplicates); //[1, 1, 2, 2]

/* Array对象的indexOf方法用于比较数组项。 IE是唯一一个原生不支持它的主流浏览器,但它很容易实现: * /

Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    i= i || 0;
    var L= this.length;
    while(i<L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1 && dups.indexOf(itm)== -1){
            dups[dups.length]= itm;
        }
    }
    return dups;
}

var a1= [1, 22, 3, 2, 2, 3, 3, 4, 1, 22, 7, 8, 9];

警报(getarrayduplicates (a1));

对于非常大的数组,可以更快地从数组中删除找到的重复项,这样就不会再次查看它们:

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1){
            dups[dups.length]= itm;
            while(A.indexOf(itm)!= -1){
                A.splice(A.indexOf(itm), 1);
            }
        }
    }
    return dups;
}

从Raphael Montanaro的回答,它可以改进使用数组/对象项如下。

function eliminateDuplicates(arr) {
  var len = arr.length,
      out = [],
      obj = {};

  for (var key, i=0; i < len; i++) {
    key = JSON.stringify(arr[i]);
    obj[key] = (obj[key]) ? obj[key] + 1 : 1;
  }
  for (var key in obj) {
    out.push(JSON.parse(key));
  }
  return [out, obj];
}

注意:对于不支持JSON的浏览器,需要使用JSON库。