JavaScript Program to Compare Elements of Two Arrays

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example 1 : Compare Arrays Using JSON.stringify()

Output

The arrays have the same elements.

The JSON.stringify() method converts an array into JSON string.

JSON.stringify([1, 3, 5, 8]); // "[1,3,5,8]"

Then, the two array strings are compared using ==.


Example 2: Compare Arrays using for Loop

Output

The arrays have the same elements.

In the above program,

The length of the array elements are compared using the length property. If both arrays have different lengths, false is returned.

Else,

  • The for loop is used to iterate through all the elements of the first array.
  • During each iteration, elements of the first array are compared to corresponding elements of the second array.
    arr1[i] != arr2[i]
  • If the corresponding array elements of both arrays are not equal, false is returned and the loop terminates.
  • If all elements are equal, true is returned.

Note: The above program does not work if the array element contains objects.

For example,

array1 = [1, {a : 2}, 3, 5];