简体   繁体   中英

How to get the unmatched array value from array in javascript with minimum complexity?

Hi I am new to java script i want some solution for the below scenario. I have a multidimensional array of coordinates

var coordinateArr = [ [[45.56,45.57],[44.36,44.37]],
                      [[42.26,42.37],[42.46,42.57]],
                      [[41.56,41.57],[41.36,41.37],[41.26,41.27]] 
                    ];

and i have an another multidimensional array like

var  anotherArr = [ [[41.56,41.57],[41.36,41.37],[41.26,41.27]], 
                     [[42.26,42.37],[42.46,42.57]]
                  ]; 

Now i want to extract the unmatched value from coordinateArr like

var unmatchedArr= [[[45.56,45.57],[44.36,44.37]]];

How can I do this?

Javascript does array comparisons by reference so you can't simple test if an array from one group is in another unless they are the same object. You need to either test each value or convert the array to something that compares by value like a string. For arrays you can use JSON.stringify . If you make a Set out of anotherArr you can then compare in a filter with Set.has()

 var coordinateArr = [ [[45.56,45.57],[44.36,44.37]], [[42.26,42.37],[42.46,42.57]], [[41.56,41.57],[41.36,41.37],[41.26,41.27]] ]; var anotherArr = [ [[41.56,41.57],[41.36,41.37],[41.26,41.27]], [[42.26,42.37],[42.46,42.57]] ]; let keys = new Set(anotherArr.map(JSON.stringify)) let filtered = coordinateArr.filter(arr => !keys.has(JSON.stringify(arr))) console.log(filtered) 

Try filter ing out the array elements that are not include d in the other array:

 var coordinateArr = [ [ [45.56, 45.57], [44.36, 44.37] ], [ [42.26, 42.37], [42.46, 42.57] ], [ [41.56, 41.57], [41.36, 41.37], [41.26, 41.27] ] ]; var anotherArr = [ [ [41.56, 41.57], [41.36, 41.37], [41.26, 41.27] ], [ [42.26, 42.37], [42.46, 42.57] ] ]; var unmatchedArr = coordinateArr.filter(e => !anotherArr.includes(e)); console.log(unmatchedArr); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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