仅使用下划线检查是否存在重复的数组对 [英] Check if duplicate array pairs exist using underscore only

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

问题描述

我想知道如何检查数组中的重复值对是否作为 javascript 中较大数组的一部分存在.你可以看到有一对重复的 [1,2] - 所以函数应该只返回 true.即

I am wondering how I can check if a duplicate pair of values in an array exist as part of a larger array in javascript. You can see there is a duplicate pair of [1,2] - so the function should just return true. i.e

var arr = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [1,2]]

我尝试使用这种逻辑,它给了我一个干净的数组和一个真实"

I have tried using this logic which gives me a clean array and a "true"

var unique = [];
var done = []; var dup = false;
for(var x = 0; x < arr.length; x++) {
    var myStr = arr[x].toString();

    if(done.indexOf(myStr) != -1) {
        // val already exist, ignore
        dup = true;
        continue;
    }

    done.push(myStr);
    unique.push(arr[x]);
}

但我想知道使用 Underscore 是否有更优雅的东西?

But I was wondering if there is something more elegant using Underscore ?

推荐答案

最短的方法是使用 _.uniqJSON.stringify:

The shortest way would be to use _.uniq and JSON.stringify:

function unique(arr) {
    return _.uniq(arr, JSON.stringify).length === arr.length;
}

但这不会短路,因此与您可以做到的其他方式相比,它有点慢.Tomalak 的第二个函数应该更快.

But that doesn't short-circuit, so it's somewhat slow compared to the other ways you could do it. Tomalak's second function should be faster.

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

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