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

前端 未结 8 2034
时光说笑
时光说笑 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:45

    This will do the job on any array and is probably about as optimized as possible for handling the general case (finding a duplicate in any possible array). For more specific cases (e.g. arrays containing only strings) you could do better than this.

    function hasDuplicate(arr) {
        var i = arr.length, j, val;
    
        while (i--) {
            val = arr[i];
            j = i;
            while (j--) {
                if (arr[j] === val) {
                    return true;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题