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

前端 未结 8 2033
时光说笑
时光说笑 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: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;
    }
    

提交回复
热议问题