查找是否在数组中重复了两个数组,然后选择它们 [英] Find if two arrays are repeated in array and then select them
问题描述
我在主/父数组中有多个数组,如下所示:
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 repeatedArrays
将是 [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屋!