javascript 检查数组是否包含重复值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19655975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:21:59  来源:igfitidea点击:

Check if an array contains duplicate values

javascript

提问by milan m

I wanted to write a javascript function which checks if array contains duplicate values or not.

我想编写一个 javascript 函数来检查数组是否包含重复值。

I have written the following code but its giving answer as "true" always.

我已经编写了以下代码,但它总是给出“真”的答案。

Can anybody please tell me what am I missing.

谁能告诉我我错过了什么。

function checkIfArrayIsUnique(myArray) 
    {
        for (var i = 0; i < myArray.length; i++) 
        {
            for (var j = 0; j < myArray.length; j++) 
            {
                if (i != j) 
                {
                    if (myArray[i] == myArray[j]) 
                    {
                        return true; // means there are duplicate values
                    }
                }
            }
        }
        return false; // means there are no duplicate values.
    }

采纳答案by NPE

You got the return values the wrong way round:

您以错误的方式获得了返回值:

  • As soon as you find two values that are equal, you can conclude that the array is notunique and return false.

  • At the very end, after you've checked all the pairs, you can return true.

  • 一旦找到两个相等的值,您就可以得出数组不是唯一的结论并返回false

  • 最后,在检查完所有对后,您可以返回true

If you do this a lot, and the arrays are large, you might want to investigate the possibility of sorting the array and then only comparing adjacent elements. This will have better asymptotic complexity than your current method.

如果您经常这样做,并且数组很大,您可能需要研究对数组进行排序然后只比较相邻元素的可能性。这将比您当前的方法具有更好的渐近复杂性。

回答by natetitterton

An easy solution, if you've got ES6, uses Set:

一个简单的解决方案,如果你有 ES6,使用Set

function checkIfArrayIsUnique(myArray) {
  return myArray.length === new Set(myArray).size;
}

let uniqueArray = [1, 2, 3, 4, 5];
console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);

let nonUniqueArray = [1, 1, 2, 3, 4, 5];
console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);

回答by CD..

This should work with only one loop:

这应该只适用于一个循环:

function checkIfArrayIsUnique(arr) {
    var map = {}, i, size;

    for (i = 0, size = arr.length; i < size; i++){
        if (map[arr[i]]){
            return false;
        }

        map[arr[i]] = true;
    }

    return true;
}

回答by ofir_aghai

let arr = [11,22,11,22];

let hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
// hasDuplicate = true

True -> array has duplicates

False -> uniqe array

True -> 数组有重复项

错误 -> 唯一数组

回答by MildlySerious

Assuming you're targeting browsers that aren't IE8,

假设您的目标浏览器不是 IE8,

this would work as well:

这也可以:

function checkIfArrayIsUnique(myArray) 
{
    for (var i = 0; i < myArray.length; i++) 
    {
        if (myArray.indexOf(myArray[i]) !== myArray.lastIndexOf(myArray[i])) { 
            return false; 
        } 
    } 
    return true;   // this means not unique
}

回答by sharad-garg

The best solution ever.

有史以来最好的解决方案。

 Array.prototype.checkIfArrayIsUnique = function() {
    this.sort();    
    for ( var i = 1; i < this.length; i++ ){
        if(this[i-1] == this[i])
            return false;
    }
    return true;
    }

回答by Alex Ticovschi

function hasNoDuplicates(arr) { return arr.every(num => arr.indexOf(num) === arr.lastIndexOf(num)); }

function hasNoDuplicates(arr) { return arr.every(num => arr.indexOf(num) === arr.lastIndexOf(num)); }

hasNoDuplicatesaccepts an array and returns trueif there are no duplicate values. If there are any duplicates, the function returns false.

hasNoDuplicates接受一个数组并true在没有重复值时返回。如果有任何重复,函数返回false

回答by D_N

Wrote this to initialize a new array of length uniqueIndexCount. It's presented here minus unrelated logic.

写这个来初始化一个长度为 uniqueIndexCount 的新数组。它在此处减去不相关的逻辑。

    public Vector3[] StandardizeVertices(Vector3[] dimensions, int standard)
    {
        //determine the number of unique dimension vectors
        int uniqueIndexCount = 0;
        for (int a=0; a < dimensions.Length; ++a)
        {
            int duplicateIndexCount = 0;
            for (int b = a; b < dimensions.Length; ++b)
            {
                if(a!=b && dimensions[a] == dimensions[b])
                {
                    duplicateIndexCount++;
                }
            }
            if (duplicateIndexCount == 0)
            {
                uniqueIndexCount++;
            }
        }
        Debug.Log("uniqueIndexCount: "+uniqueIndexCount);
        return dimensions;
    }

回答by Morris S

Without a for loop, only using Map().

没有for loop,只有using Map()

You can also return the duplicates.

您也可以返回重复项。

(function(a){
  let map = new Map();

  a.forEach(e => {
    if(map.has(e)) {
      let count = map.get(e);
      console.log(count)
      map.set(e, count + 1);
    } else {
      map.set(e, 1);
    }
  });

  let hasDup = false;
  let dups = [];
  map.forEach((value, key) => {
    if(value > 1) {
      hasDup = true;
      dups.push(key);
    }
  });
   console.log(dups);
   return hasDup;
 })([2,4,6,2,1,4]);

回答by Sajjan Sarkar

Here's an O(n) solution:

这是一个 O(n) 解决方案:

function hasDupes(arr) {
  /* temporary object */
  var uniqOb = {};
  /* create object attribute with name=value in array, this will not keep dupes*/
  for (var i in arr)
    uniqOb[arr[i]] = "";
  /* if object's attributes match array, then no dupes! */
  if (arr.length == Object.keys(uniqOb).length)
    alert('NO dupes');
  else
    alert('HAS dupes');


}
var arr = ["1/1/2016", "1/1/2016", "2/1/2016"];
hasDupes(arr);

https://jsfiddle.net/7kkgy1j3/

https://jsfiddle.net/7kkgy1j3/