How to compare two JavaScript array objects using jQuery/JavaScript?



In JavaScript, an array is an object with an index as a key and array values as a value of a particular key of an array object. Sometimes, we require to check if two arrays are the same or not.

The first solution that comes to mind is using the equality operator and comparing them like array1 == array2. Oops! It will not work as the array is an object, and we can’t compare two objects directly in JavaScript. So, we have to compare every element of the array.

In this tutorial, we will learn to compare two JavaScript array objects using various approaches.

Use the sort() method of JavaScript and compare every element

The sort() method allows us to sort the array values in JavaScript. After that, we can use the for loop to compare the element at each index in the array. If an element at any index mismatches, we can say that both array objects are different.

Syntax

Users can follow the syntax below to compare two array objects using the sort() method and for-loop.

// sort arrays first
arra1.sort();
array2.sort();
   if (array1.length != array2.length) {
      // arrays are not the same
   } else {
      for () {
         // if elements at index i are not the same, return false
      }
   }
}
// both arrays are the same

Algorithm

Users can follow the below algorithm.

  • Step 1 − Use the sort() method to sort both arrays.

  • Step 2 − Compare the length of both arrays; if it is not the same, return false, representing both arrays are not the same.

  • Step 3 − If the length of both arrays is the same, use for loop to iterate through both arrays.

  • Step 4 − Compare the elements of both arrays at every index, and if the elements at the index don’t match, return false.

  • Step 5 − If all element matches in both array, both arrays are the same.

Example

In the example below, we created two numbers array and used the sort() method to sort them. After that, we used the for-loop to compare every element of both arrays.

In the output, users can see that both arrays are the same as both arrays contain the same values.

<html>
<body>
   <h3>Using the <i>array.sort()</i> method and <i>for</i> loop to check if two arrays are the same using JavaScript </h2>
   <button onclick = "checkArray()"> Compare arrays </button>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array1 = [32, 32, 54, 1, 2, 3, 4];
      let array2 = [1, 2, 3, 4, 32, 54, 32];
      output.innerHTML += "The first array values are " + array1 + "<br>";
      output.innerHTML += "The second array values are " + array2 + "<br>";
      function checkArray() {
         array1.sort();
         array2.sort();
         if (array1.length != array2.length) {
            output.innerHTML += "Both arrays are not same!";
            return false;
         } else {
            for (let i = 0; i < array1.length; i++) {
               if (array1[i] != array2[i]) {
                  output.innerHTML += "Both arrays are not same!";
                  return false;
               }
            }
         }
         output.innerHTML += "Both arrays are the same!";
         return true;
      }
   </script>
</body>
</html>

Use the forEach loop and indexOf() method

We can use the forEach loop to iterate through every array element. The indexOf() method finds the first occurrence of the element in the array and returns -1 if the reference array doesn’t contain the element.

Syntax

Users can follow the syntax below to use the forEach loop and indexOf() methods to compare two array objects.

if (array2.length != array1.length) {
   // array are not the same
   return false;
} else {
   array1.forEach((element) => {
      if (array2.indexOf(element) == -1) {
         return false;
      }
   })
}

Algorithm

In this algorithm, we don’t need to sort the arrays like the first approach.

  • Step 1 − Check if the length of both arrays is the same; If not, return false.

  • Step 2 − If the lengths are the same, use the forEach() loop to iterate through every element.

  • Step 3 − For every element of array1, check if it exists in array2 using the indexOf() method.

  • Step 4 − If the indexOf() method returns -1 for any single element, it means both arrays are not the same.

Example

In the example below, when the user clicks the button, it will invoke a compareArray() function. The compareArray() function compares the two arrays of string elements.

In the output, users can observe that both arrays are not the same, as the values of both arrays are different.

<html>
<body>
   <h3>Using the <i>forEach() loop and indexOf() method</i> to check if two arrays are the same using JavaScript </h3>
   <button onclick = "compareArray()"> Compare arrays</button>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array1 = ["Hello", "Hi", "How"];
      let array2 = ["Are", "You", "!"];
      output.innerHTML += "The first array values are " + array1 + " <br>";
      output.innerHTML += "The second array values are " + array2 + " <br>";
      function compareArray() {
         var isSame = true;
         if (array2.length != array1.length) {
            output.innerHTML += "Both arrays are not same!";
            return false;
         } else {
            array2.forEach((element) => {
               if (array1.indexOf(element) == -1) {
                  isSame = false;
               }
            })
         }
         if (isSame) {
            output.innerHTML += "Both arrays are the same!";
         } else {
            output.innerHTML += "Both arrays are not same!";
         }
         return true;
      }
   </script>
</body>
</html>

We have learned two different approaches to compare two arrays in JavaScript. The users can use the first approach to compare the arrays containing duplicate values, and the second approach is only useful to compare the array containing unique values.

Also, users can use the JSON.stringify() method to compare the array of objects and sorted arrays.


Advertisements