fastest way to detect if duplicate entry exists in javascript array?

前端 未结 8 2025
时光说笑
时光说笑 2021-02-06 09:54
var arr = [\'test0\',\'test2\',\'test0\'];

Like the above,there are two identical entries with value \"test0\",how to check it most efficiently?

8条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-06 10:37

    You can convert the array to to a Set instance, then convert to an array and check if the length is same before and after the conversion.

    const hasDuplicates = (array) => {
      const arr = ['test0','test2','test0'];
      const set1 = new Set(array);
      const uniqueArray = [...set1];
      
      return array.length !== uniqueArray.length;
    };
    
    console.log(`Has duplicates : ${hasDuplicates(['test0','test2','test0'])}`);
    console.log(`Has duplicates : ${hasDuplicates(['test0','test2','test3'])}`);

提交回复
热议问题