I have two integer arrays which contain numeric values. I want to look through both lists and check for commonality (or lack of) between the lists. I.e. I want to iterate through the array(s) and find those items which appear in both lists, while in a separate function I want to go through the arrays and find items which are in the first and not in the second.
The obvious way of doing this is nested for loops:
var containedInFirst = false; for (var primaryID = 0; primaryID < PrimaryArray.length; primaryID++) { containedInFirst = false; for (var secondaryID = 0; secondaryID < SecondaryArray.length; secondaryID++) { if (PrimaryArray [primaryID] === SecondaryArray[secondaryID]) { containedInFirst = true; break; } } //Do some more stuff based on the value of containedInFirst here }
But given the lists could contain hundreds or thousands of records this is quite a bit of itteration and processor intensive. I was therefore wondering if there is a more efficient way of executing the above code? Not just the actual searching, but something more efficient than an Integer array as the container for the values, or just not using nested for loops to traverse and compare the content.
Any thoughts on more efficient or elegant solutions?
While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.
Everyone is overly complicating this. Here's a one liner:
var isEqual = (JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With