Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: efficiently compare two integer arrays

Tags:

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?

like image 970
LDJ Avatar asked Nov 16 '10 11:11

LDJ


People also ask

Can we compare two arrays in Javascript?

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.


1 Answers

Everyone is overly complicating this. Here's a one liner:

var isEqual = (JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort())); 
like image 144
Timothy Perez Avatar answered Sep 19 '22 00:09

Timothy Perez