How To Check If Two Arrays Are Equal Using JavaScript
Good afternoon fellow developers,
I've been doing some checking if two arrays with same data types are equal in my client-side validation. A popular solution presented in stackoverflow is the function below.
This does fulfill the requirement but performs sorting of elements first which tends to slow the comparison. So, I tend to modify the function to use indexOf() function which will check if an element in the first array object exists on the second array. Thus eliminate the sorting mechanism.
See fiddle for the demo: Check If Two Arrays Are Equal
I've been doing some checking if two arrays with same data types are equal in my client-side validation. A popular solution presented in stackoverflow is the function below.
function CheckArrayEqualSort (arr1, arr2) { if (arr1.length !== arr2.length) { return false; } var ar1 = arr1.concat().sort(); var ar2 = arr2.concat().sort(); for (var i = 0; i < arr1.length; i++) { if (ar1[i] !== ar2[i]) { return false; } } return true; };
function CheckArrayEqual (arr1, arr2) { if (arr1.length !== arr2.length) { return false; } for (var i = 0; i < arr1.length; i++) { if (arr2.indexOf(arr1[i]) < 0) { return false; } } return true; };
Comments
Post a Comment