Donate

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.
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;
};
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.
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;
};
See fiddle for the demo: Check If Two Arrays Are Equal

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.