我正在寻找一种在数组中的数组之间进行比较的方法。
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/