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

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

    There are lots of answers here but not all of them "feel" nice... So I'll throw my hat in.

    If you are using lodash:

    function containsDuplicates(array) {
      return _.uniq(array).length !== array.length; 
    }
    

    If you can use ES6 Sets, it simply becomes:

    function containsDuplicates(array) {
      return array.length !== new Set(array).size
    }
    

    With vanilla javascript:

    function containsDuplicates(array) {
      return array
        .sort()
        .some(function (item, i, items) {
          return item === items[i + 1]
        })
    }
    

    However, sometimes you may want to check if the items are duplicated on a certain field.

    This is how I'd handle that:

    containsDuplicates([{country: 'AU'}, {country: 'UK'}, {country: 'AU'}], 'country')
    
    function containsDuplicates(array, attribute) {
      return array
        .map(function (item) { return item[attribute] })
        .sort()
        .some(function (item, i, items) {
          return item === items[i + 1]
        })
    }
    

提交回复
热议问题