Using lodash to check whether an array has duplicate values

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

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 order to check an array for duplicate values.

I want to input ['foo', 'foo', 'bar'] and have the function return true. And input ['foo', 'bar', 'baz'] and have the function return false.

回答1:

You can try this code:

function hasDuplicates(a) {   return _.uniq(a).length !== a.length;  }  var a = [1,2,1,3,4,5]; var b = [1,2,3,4,5,6];  document.write(hasDuplicates(a), ',',hasDuplicates(b));


回答2:

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); 


回答3:

Well, there's always. lodash's _.uniq() function. That function actually returns a new array that only contains unique values, so checking to see if the length of the array has changed would get you your 'true' or 'false' value to return yourself, I believe.



回答4:

I don't know lodash but I submit:

_.any(_.countBy(['foo', 'foo', 'bar']), function(x){ return x > 1; }); 

The problem with all the solutions proposed so far is that the entire input array needs processing to get an answer, even if the answer is obvious from the first 2 elements of the array.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!