在 Javascript 中,如何检查数组是否有重复值?

发布于 2024-12-04 08:51:19 字数 605 浏览 0 评论 0原文

可能的重复:
在 JavaScript 数组中查找重复值的最简单方法

如何检查数组是否有重复值?

如果数组中的某些元素相同,则返回 true。否则,返回 false。

['hello','goodbye','hey'] //return false because no duplicates exist
['hello','goodbye','hello'] // return true because duplicates exist

请注意,我不关心查找重复项,只想要布尔结果数组是否包含重复项。

Possible Duplicate:
Easiest way to find duplicate values in a javascript array

How do I check if an array has duplicate values?

If some elements in the array are the same, then return true. Otherwise, return false.

['hello','goodbye','hey'] //return false because no duplicates exist
['hello','goodbye','hello'] // return true because duplicates exist

Notice I don't care about finding the duplication, only want Boolean result whether arrays contains duplications.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

风蛊 2024-12-11 08:51:21

为什么使用这种方法:

我认为这是处理多个数组和循环时最好的方法,这个例子非常简单,但在某些情况下,例如迭代多个循环并迭代对象时,是最可靠和最佳的方法。

说明:

在这个例子中,数组被迭代,element与array[i]相同,i是循环当前所在数组的位置,然后函数检查读取数组中的位置初始化为空,如果该元素不在读取数组中,它将返回-1,并且将被推送到读取数组,否则它将返回其位置并且不会被推送,一旦所有元素数组已被迭代,读取的数组将被打印到控制台

let array = [1, 2, 3, 4, 5, 1, 2, 3, 5]
let read = []

array.forEach(element => {
  if (read.indexOf(element) == -1) {
    read.push(element)
    console.log("This is the first time" + element + " appears in the array")
  } else {
    console.log(element + " is already in the array")
  }
})

console.log(read)

Why use this method:

I think this is the best way to do it when dealing with multiple arrays and loops, this exaple is very simple but in some cases such when iterating with several loops and iterating through objects this is the most reliable and optimal way to do it.

Explanation:

In this example the array is iterated, element is the same as array[i] i being the position of the array that the loop is currently on, then the function checks the position in the read array which is initialized as empty, if the element is not in the read array it'll return -1 and it'll be pushed to the read array, else it'll return its position and won't be pushed, once all the element of array has been iterated the read array will be printed to console

let array = [1, 2, 3, 4, 5, 1, 2, 3, 5]
let read = []

array.forEach(element => {
  if (read.indexOf(element) == -1) {
    read.push(element)
    console.log("This is the first time" + element + " appears in the array")
  } else {
    console.log(element + " is already in the array")
  }
})

console.log(read)

不可一世的女人 2024-12-11 08:51:21

使用 Set 的解决方案的一个好处是查找列表中现有项目的 O(1) 性能,而不必循环遍历它。

使用 Some 的解决方案的一个好处是,当尽早发现重复项时会发生短路,因此当条件已满足时,您不必继续评估数组的其余部分。

将两者结合起来的一种解决方案是增量构建一个集合,如果集合中存在当前元素,则提前终止,否则添加它并继续处理下一个元素。

const hasDuplicates = (arr) => {
  let set = new Set()
  return arr.some(el => {
    if (set.has(el)) return true
    set.add(el)
  })
}

hasDuplicates(["a","b","b"]) // true
hasDuplicates(["a","b","c"]) // false

根据JSBench.me,对于各种用例来说应该表现得很好。设置大小方法在没有重复的情况下是最快的,而检查 some + indexOf 在非常早期的重复中是最快的,但是这个解决方案在这两种情况下都表现良好,使其成为一个很好的全面实现。

One nice thing about solutions that use Set is O(1) performance on looking up existing items in a list, rather than having to loop back over it.

One nice thing about solutions that use Some is short-circuiting when the duplicate is found early, so you don't have to continue evaluating the rest of the array when the condition is already met.

One solution that combines both is to incrementally build a set, early terminate if the current element exists in the set, otherwise add it and move on to the next element.

const hasDuplicates = (arr) => {
  let set = new Set()
  return arr.some(el => {
    if (set.has(el)) return true
    set.add(el)
  })
}

hasDuplicates(["a","b","b"]) // true
hasDuplicates(["a","b","c"]) // false

According to JSBench.me, should preform pretty well for the varried use cases. The set size approach is fastest with no dupes, and checking some + indexOf is fatest with a very early dupe, but this solution performs well in both scenarios, making it a good all-around implementation.

森林散布 2024-12-11 08:51:21
    this.selectedExam = [];
    // example exam obj: {examId:1, name:'ExamName'}
    onExamSelect(exam: any) {
    if(!this.selectedExam.includes(exam?.name)){ 
      this.selectedExam.push(exam?.name);
    }}

在上面的代码中,我采用了一个数组,并在触发特定函数(onExamSelect)时,我们检查重复项并推送唯一元素。

    this.selectedExam = [];
    // example exam obj: {examId:1, name:'ExamName'}
    onExamSelect(exam: any) {
    if(!this.selectedExam.includes(exam?.name)){ 
      this.selectedExam.push(exam?.name);
    }}

In the above code, I have taken an array and on triggering a particular function (onExamSelect) we are checking duplicates and pushing unique elements.

夏九 2024-12-11 08:51:21

到 2023 年,这是对对象数组执行此操作的最佳方法,检查严格相等性。 Set 无法做到这一点。

const answerTableRows = [
    { rk: "u", pk: "1", },
    { rk: "u", pk: "2", },
    { rk: "u", pk: "1", }, // get rid of this one
    { rk: "x", pk: "y" },
];
let uniqueAnswerTableRows = answerTableRows.filter((v, i, a) => {
    return a.findIndex(t => (t.rk === v.rk && t.pk === v.pk)) === i;
});
console.log(uniqueAnswerTableRows);
// [ { rk: 'u', pk: '1' }, { rk: 'u', pk: '2' }, { rk: 'x', pk: 'y' } ]

In 2023, this is the best way to do it for an array of objects, checking strict equality. A Set cannot do this.

const answerTableRows = [
    { rk: "u", pk: "1", },
    { rk: "u", pk: "2", },
    { rk: "u", pk: "1", }, // get rid of this one
    { rk: "x", pk: "y" },
];
let uniqueAnswerTableRows = answerTableRows.filter((v, i, a) => {
    return a.findIndex(t => (t.rk === v.rk && t.pk === v.pk)) === i;
});
console.log(uniqueAnswerTableRows);
// [ { rk: 'u', pk: '1' }, { rk: 'u', pk: '2' }, { rk: 'x', pk: 'y' } ]
十二 2024-12-11 08:51:21
function hasAllUniqueChars( s ){ 
    for(let c=0; c<s.length; c++){
        for(let d=c+1; d<s.length; d++){
            if((s[c]==s[d])){
                return false;
            }
        }
    }
    return true;
}
function hasAllUniqueChars( s ){ 
    for(let c=0; c<s.length; c++){
        for(let d=c+1; d<s.length; d++){
            if((s[c]==s[d])){
                return false;
            }
        }
    }
    return true;
}
人│生佛魔见 2024-12-11 08:51:20

ES6 的单线解决方案

const arr1 = ['hello','goodbye','hey'] 
const arr2 = ['hello','goodbye','hello'] 

const hasDuplicates = (arr) => arr.length !== new Set(arr).size;
console.log(hasDuplicates(arr1)) //return false because no duplicates exist
console.log(hasDuplicates(arr2)) //return true because duplicates exist

const s1 = ['hello','goodbye','hey'].some((e, i, arr) => arr.indexOf(e) !== i)
const s2 = ['hello','goodbye','hello'].some((e, i, arr) => arr.indexOf(e) !== i);

console.log(s1) //return false because no duplicates exist
console.log(s2) //return true because duplicates exist

One line solutions with ES6

const arr1 = ['hello','goodbye','hey'] 
const arr2 = ['hello','goodbye','hello'] 

const hasDuplicates = (arr) => arr.length !== new Set(arr).size;
console.log(hasDuplicates(arr1)) //return false because no duplicates exist
console.log(hasDuplicates(arr2)) //return true because duplicates exist

const s1 = ['hello','goodbye','hey'].some((e, i, arr) => arr.indexOf(e) !== i)
const s2 = ['hello','goodbye','hello'].some((e, i, arr) => arr.indexOf(e) !== i);

console.log(s1) //return false because no duplicates exist
console.log(s2) //return true because duplicates exist

奈何桥上唱咆哮 2024-12-11 08:51:20

您可以使用 SET 删除重复项并进行比较,如果将数组复制到集合中,它将删除所有重复项。然后简单地将数组的长度与集合的大小进行比较。

function hasDuplicates(a) {

  const noDups = new Set(a);

  return a.length !== noDups.size;
}

You could use SET to remove duplicates and compare, If you copy the array into a set it will remove any duplicates. Then simply compare the length of the array to the size of the set.

function hasDuplicates(a) {

  const noDups = new Set(a);

  return a.length !== noDups.size;
}
情未る 2024-12-11 08:51:20

另一种方法(也适用于数组中的对象/数组元素1)可能是2

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

另请参阅...

1 需要支持 JSON 的浏览器,或一个 JSON 库 如果没有。
2 edit: 函数现在可用于简单检查或返回重复值数组

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

庆幸我还是我 2024-12-11 08:51:20

您可以利用 indexOflastIndexOf。如果两个索引不相同,则有重复。

function containsDuplicates(a) {
  for (let i = 0; i < a.length; i++) {
    if (a.indexOf(a[i]) !== a.lastIndexOf(a[i])) {
      return true
    }
  }
  return false
}

You can take benefit of indexOf and lastIndexOf. if both indexes are not same, you have duplicate.

function containsDuplicates(a) {
  for (let i = 0; i < a.length; i++) {
    if (a.indexOf(a[i]) !== a.lastIndexOf(a[i])) {
      return true
    }
  }
  return false
}
烟凡古楼 2024-12-11 08:51:20

如果要处理简单值,则可以使用array.some()indexof()

例如,让我们说vals is [“ b”,“ a”,“ a”,“ c”]

const allUnique = !vals.some((v, i) => vals.indexOf(v) < i);

如果任何任何表达式返回true,则会返回true。在这里,我们将迭代值(从索引0),然后调用索引(),该索引将返回给定项目的第一次出现的索引(或在数组中不在数字中)。如果它的ID较小,则在当前的ID之前必须至少有一个相同的值。因此,迭代3将返回true,因为“ a”(在索引2)首先在索引1上找到。

If you are dealing with simple values, you can use array.some() and indexOf()

for example let's say vals is ["b", "a", "a", "c"]

const allUnique = !vals.some((v, i) => vals.indexOf(v) < i);

some() will return true if any expression returns true. Here we'll iterate values (from the index 0) and call the indexOf() that will return the index of the first occurrence of given item (or -1 if not in the array). If its id is smaller that the current one, there must be at least one same value before it. thus iteration 3 will return true as "a" (at index 2) is first found at index 1.

指尖微凉心微凉 2024-12-11 08:51:20

很简单,你可以使用 Array.prototype.every 函数

function isUnique(arr) {
  const isAllUniqueItems = input.every((value, index, arr) => {
    return arr.indexOf(value) === index; //check if any duplicate value is in other index
  });

  return isAllUniqueItems;
}

is just simple, you can use the Array.prototype.every function

function isUnique(arr) {
  const isAllUniqueItems = input.every((value, index, arr) => {
    return arr.indexOf(value) === index; //check if any duplicate value is in other index
  });

  return isAllUniqueItems;
}
你又不是我 2024-12-11 08:51:19

如果您有 ES2015 环境(截至撰写本文时:io.js、IE11、Chrome、Firefox、WebKit nightly),那么以下内容将起作用,并且速度会很快(即 O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

如果您只需要字符串数组中的值,以下内容将起作用:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

我们使用“哈希表”valuesSoFar,其键是迄今为止我们在数组中看到的值。我们使用 in 进行查找,看看该值是否已经被发现;如果是这样,我们跳出循环并返回true


如果您需要一个不仅仅适用于字符串值的函数,那么以下函数也可以,但性能不高;它是 O(n2) 而不是 O(n)。

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

区别在于,我们使用数组而不是 valuesSoFar 的哈希表,因为 JavaScript“哈希表”(即对象)只有字符串键。这意味着我们失去了 in 的 O(1) 查找时间,而是获得了 indexOf 的 O(n) 查找时间。

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文