How to check identical array in most efficient way?

JavascriptArraysComparison

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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;
}

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionssdesignView Question on Stackoverflow
Solution 1 - JavascriptpalswimView Answer on Stackoverflow
Solution 2 - JavascriptAdamView Answer on Stackoverflow