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

前端 未结 8 2022
时光说笑
时光说笑 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:51
        var index = myArray.indexOf(strElement);
        if (index < 0) {
            myArray.push(strElement);
            console.log("Added Into Array" + strElement);
        } else {
            console.log("Already Exists at " + index);
        }
    
    0 讨论(0)
  • 2021-02-06 10:52

    Sorting is O(n log n) and not O(n). Building a hash map is O(n). It costs more memory than an in-place sort but you asked for the "fastest." (I'm positive this can be optimized but it is optimal up to a constant factor.)

    function hasDuplicate(arr) {
      var hash = {};
      var hasDuplicate = false;
       arr.forEach(function(val) {
         if (hash[val]) {
           hasDuplicate = true;
           return;
         }
         hash[val] = true;
      });
      return hasDuplicate;
    }
    
    0 讨论(0)
提交回复
热议问题