Using lodash to check whether an array has duplicate values

前端 未结 6 686
独厮守ぢ
独厮守ぢ 2020-12-30 21:57

What do you all think would be the best (best can be interpreted as most readable or most performant, your choice) way to write a function using the lodash utilities in orde

6条回答
  •  心在旅途
    2020-12-30 22:39

    You could check that there is _.some element in the array which does not return its own location when looked up in the array. In other words, there is at least one element which has a match earlier in the array.

    function hasDuplicates(array) {
        return _.some(array, function(elt, index) { 
            return array.indexOf(elt) !== index; 
        });
    }
    

    Perhaps this is faster than the _.uniq solution, since it will identify the first duplicated element right away without having to compute the entire unique-ified array.

    Or, depending on your coding style and desire for readability, and if you want to use ES6 arrow functions for brevity:

    var earlierMatch  = (elt, index, array) => array.indexOf(elt) !== index;
    var hasDuplicates = array => _.some(array, earlierMatch);
    

提交回复
热议问题