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

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

    Assuming all you want is to detect how many duplicates of 'test0' are in the array. I guess an easy way to do that is to use the join method to transform the array in a string, and then use the match method.

    var arr= ['test0','test2','test0'];
    var str = arr.join();
    
    console.log(str) //"test0,test2,test0"
    
    var duplicates = str.match(/test0/g);
    var duplicateNumber = duplicates.length;
    
    console.log(duplicateNumber); //2
    

提交回复
热议问题