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

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

    Loop stops when found first duplicate:

    function has_duplicates(arr) {
    
        var x = {}, len = arr.length;
        for (var i = 0; i < len; i++) {
            if (x[arr[i]]) {
                 return true;
            }
            x[arr[i]] = true;
        }
        return false;
    
    }
    

    Edit (fix 'toString' issue):

    function has_duplicates(arr) {
    
        var x = {}, len = arr.length;
        for (var i = 0; i < len; i++) {
            if (x[arr[i]] === true) {
                 return true;
            }
            x[arr[i]] = true;
        }
        return false;
    
    }
    

    this will correct for case has_duplicates(['toString']); etc..

提交回复
热议问题