javascript - 比较数组中的数组

标签 javascript arrays

我正在寻找一种在数组中的数组之间进行比较的方法。

let small = [[1, 3], [2, 2], [2, 3], [3, 0]];

let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

例如,我希望能够找出 small 中的数组中有多少在 large 中找到。某些函数,将上面的数组作为参数,将返回 2,因为 [2, 2][3, 0] 来自 small 位于 large 中。

你会怎样做?

最佳答案

您可以将其中一个数组转换为 Set哈希值,并且比 filter使用该集合的第二个数组:

const small = [[1, 3], [2, 2], [2, 3], [3, 0]];

const large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

const containsCount = (arr1, arr2, hashFn) => {
  const arr1Hash = new Set(arr1.map(hashFn));
  
  return arr2.filter(s => arr1Hash.has(hashFn(s))).length;
}

const result = containsCount(small, large, ([a, b]) => `${a}-${b}`); 

console.log(result);

关于javascript - 比较数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110967/

相关文章:

javascript - Ajax - Json 与文本性能

javascript - jQuery 无法处理 AJAX 加载的 html 内容

arrays - golang : gzip or zlib compression of byte array sporadically hangs

c++ - 如何在 C++ 的二维字符数组中输入不同长度的字符串?

php - 产品 ID 未存储在数据库中

c - 完美数、数组、验证和运算

java - 有没有其他方法可以根据需要填充这个数组

javascript - Twitter Bootstrap 2 javascript 插件不工作

javascript - 将鼠标悬停在 Google 搜索中的链接上会显示不同的 URL

javascript - fingerprintjs 未在 chrome 扩展中加载