查找两个数组是否在数组中重复,然后选择它们 [英] Find if two arrays are repeated in array and then select them

查看:33
本文介绍了查找两个数组是否在数组中重复,然后选择它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主/父数组中有多个数组,如下所示:

I have multiple arrays in a main/parent array like this:

var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]];

为了更简单的阅读,这里是数组:

here are the array's for simpler reading:

[1, 17]
[1, 17]
[1, 17]
[2, 12]
[5, 9]
[2, 12]
[6, 2]
[2, 12]
[2, 12]

我想选择重复 3 次或更多次 (> 3) 的数组并将其分配给一个变量.所以在这个例子中,var repeatArrays 将是 [1, 17][2, 12].

I want to select the arrays that are repeated 3 or more times (> 3) and assign it to a variable. So in this example, var repeatedArrays would be [1, 17] and [2, 12].

所以这应该是最终的结果:

So this should be the final result:

console.log(repeatedArrays);
>>> [[1, 17], [2, 12]]

我在这里找到了类似的东西,但它使用了 underscore.js 和 lodash.

I found something similar here but it uses underscore.js and lodash.

如何使用 javascript 甚至 jquery(如果需要)?

How could I it with javascript or even jquery (if need be)?

推荐答案

您可以参考 Map,然后按计数过滤并恢复数组.

You could take a Map with stringified arrays and count, then filter by count and restore the arrays.

var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]],
    result = Array
        .from(array.reduce(
            (map, array) =>
                (json => map.set(json, (map.get(json) || 0) + 1))
                (JSON.stringify(array)),
            new Map
         ))
        .filter(([, count]) => count > 2)
        .map(([json]) => JSON.parse(json));
        
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

使用所需数量的地图进行过滤.

Filter with a map at wanted count.

var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]],
    result = array.filter(
        (map => a => 
            (json =>
                (count => map.set(json, count) && !(2 - count))
                (1 + map.get(json) || 1)
            )
            (JSON.stringify(a))
        )
        (new Map)
    );
        
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

独一无二!

var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]],
    result = array.filter(
        (s => a => (j => !s.has(j) && s.add(j))(JSON.stringify(a)))
        (new Set)
    );
        
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于查找两个数组是否在数组中重复,然后选择它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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