JS中如何匹配嵌套数组中的重复值
我有一个数组,其中包含动态创建的嵌套数组,它看起来像这样:
[['1', '2'],['1','3', '4'],['1', '3']]
我试图通过仅从这些数组中获取重复值来实现 AND 逻辑。我的预期输出为 ['1']
因为所有嵌套数组必须包含相同的值。
// [['1', '2'],['1','3', '4'],['1', '3']]
const arrays = [...new Set(response)].filter(newSet => newSet.length > 0);
const builder = []; // array of all the id's no longer needed
// [[],[],[]]
arrays.forEach(arr => {
// []
arr.forEach(value => {
// [[], [], []]
const found = arrays.filter(a => a.find(v => v === value));
if (found.length === 0)
builder.push(value);
});
});
console.log(builder); // empty []
由于 filter()
,这给了我一个空数组。我怎样才能返回所有(在本例中为 3 个,但可能更多)数组包含的值数组?
上述输入的预期输出将为["1"]
。任何帮助表示赞赏。
I have an array which contains nested arrays that are dynamically created, it looks like this:
[['1', '2'],['1','3', '4'],['1', '3']]
I am trying to implement AND logic by getting only duplicate values from these arrays. My expected output here would be ['1']
since all nested arrays must contain the same value.
// [['1', '2'],['1','3', '4'],['1', '3']]
const arrays = [...new Set(response)].filter(newSet => newSet.length > 0);
const builder = []; // array of all the id's no longer needed
// [[],[],[]]
arrays.forEach(arr => {
// []
arr.forEach(value => {
// [[], [], []]
const found = arrays.filter(a => a.find(v => v === value));
if (found.length === 0)
builder.push(value);
});
});
console.log(builder); // empty []
This gives me an empty array because of the filter()
. How could I return an array of values that all (3 in this case but could be more) arrays contain?
Expected output with the above input would be ["1"]
. Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我了解,您需要所有数组中的公共元素
更新
显然,集合转换是不必要的,因为无论如何它必须提供每个数组共有的元素,因此从
res[0]
进行过滤应该可以from what I understand you need the common elements from all array
UPDATE
Apparently the set transformation is unnecessary since anyway it has to give the elements common to every array so filtering from
res[0]
should do您可以创建一个计数对象,其中包含每个数字的频率,然后仅检查数字的频率是否等于原始数组的长度。
You can make a count object that has the frequency of each number in it, and just check if the frequency of a number is equal to the length of the original array.
Lodash intesection 如果你不介意的话
Lodash intesection if you don't mind