Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check identical array in most efficient way? [duplicate]

I want to check if the two arrays are identical (not content wise, but in exact order).

For example:

 array1 = [1,2,3,4,5]  array2 = [1,2,3,4,5]  array3 = [3,5,1,2,4] 

Array 1 and 2 are identical but 3 is not.

Is there a good way to do this in JavaScript?

like image 677
ssdesign Avatar asked Oct 26 '10 16:10

ssdesign


People also ask

How do you check if there is a duplicate in an array?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do you find duplicates in two arrays?

You should leverage a hashmap/hashset for a substantially faster O(n) solution: void findDupes(int[] a, int[] b) { HashSet<Integer> map = new HashSet<Integer>(); for (int i : a) map. add(i); for (int i : b) { if (map. contains(i)) // found duplicate! } }

Which sorting algorithm is best for duplicates?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.


2 Answers

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {     if(arr1.length !== arr2.length)         return false;     for(var i = arr1.length; i--;) {         if(arr1[i] !== arr2[i])             return false;     }      return true; } 
like image 110
palswim Avatar answered Sep 27 '22 19:09

palswim


You could compare String representations so:

array1.toString() == array2.toString() array1.toString() !== array3.toString() 

but that would also make

array4 = ['1',2,3,4,5] 

equal to array1 if that matters to you

like image 23
Adam Avatar answered Sep 27 '22 20:09

Adam