使用lodash检查数组是否具有重复值 [英] Using lodash to check whether an array has duplicate values

查看:1288
本文介绍了使用lodash检查数组是否具有重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你认为最好的(最好的解释是最可读或最高效,你的选择)使用lodash实用程序编写函数以检查数组是否有重复值。

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.

我想输入 ['foo','foo','bar'] 并让函数返回。并输入 ['foo','bar','baz'] 并让函数返回 false

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

推荐答案

您可以尝试以下代码:

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

<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.1.0/lodash.min.js"></script>

这篇关于使用lodash检查数组是否具有重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆