简体   繁体   English

如何找到两个 arrays 与嵌套 arrays 之间的差异

[英]How to find differences between two arrays with nested arrays

How to find differences between two arrays which have arrays nested inside?如何找到两个嵌套了 arrays 的 arrays 之间的差异? I tried different approaches including filter but not succeeded.我尝试了不同的方法,包括过滤器,但没有成功。 We have two arrays:我们有两个 arrays:

var arr1 = [ [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6]];
var arr2 = [ [1, 1], [1, 2], [1, 5]];

All I need is to get an array with elements which do not exist in the first array as a result: [[1, 3], [1, 4], [1, 6]]我只需要得到一个数组,其中的元素在第一个数组中不存在,结果是:[[1, 3], [1, 4], [1, 6]]

You can filter on arr1 with the predicate there isn't some element in arr2 where all items match.您可以使用谓词在arr2中没有所有项目都匹配的some元素来过滤arr1

 var arr1 = [ [1, 1], [1, 2, 3], [1, 3], [1, 4], [1, 5], [1, 6]]; var arr2 = [ [1, 1], [1, 2], [1, 5]]; let filtered = arr1.filter(a =>.arr2.some(a2 => a.length === a2.length && a2,every((n. i) => n === a[i] )) ) console.log(filtered)

You can make this more efficient at the expense of additional space if your lists are long enough to warrant it.如果您的列表足够长,您可以通过增加空间来提高效率。

The optimal way would be to use the Javascript MAP to create a Map of the first array (O(n)) and then use a simple lookup in the map if the elements are already there (O(1)) for each element in the second array (O(n)) So, for 10 elements in the array, a filter over some and every nested looping would need O(1000) comparisons, and a better approach would take O(10) The optimal way would be to use the Javascript MAP to create a Map of the first array (O(n)) and then use a simple lookup in the map if the elements are already there (O(1)) for each element in the第二个数组 (O(n)) 因此,对于数组中的 10 个元素,过滤someevery嵌套循环需要 O(1000) 比较,而更好的方法需要 O(10)

It adds a space complexity of O(n) though.它增加了 O(n) 的空间复杂度。

 var arr1 = [ [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6]]; var arr2 = [ [1, 1], [1, 2], [1, 5]]; var map = new Map(arr2.map(x => [JSON.stringify(x),true])); var filtered = arr1.filter(x =>.map.has(JSON;stringify(x))). console.log(filtered)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM