Checking the equality of array elements (sequence dependent) in JavaScript


In this article, the given task is to check the equality of array elements (sequence dependent). Before we proceed into examples, let’s look at how the input-output scenario will look when we are checking the equality of array elements (sequence dependent) in JavaScript.

Input-Output scenario

Let’s look into the input-output scenario, where we have declared two arrays and we need to get similar elements in sequence-dependent.

Array1 = [2, 5, 6, 7, 9, 0];
Array2 = [3, 5, 0, 8, 9, 4];

Output = [5, 9]

In the above snippet, we can see that there are two arrays with elements in them. we found that 5 and 9 are the same sequence in both arrays.

Example 1

In the following example below,

  • We have declared two arrays with elements in them. By iterating the first array (array1) we are comparing every element in the first array with elements in the second array.

  • Whenever there is a match in the same sequence order, that element will be pushed into an empty array.

<!DOCTYPE html> <html> <head> <title>Checking the equality of array elements (sequence dependent) in JavaScript</title> <button onClick="func()">Click!</button> <p id="para"></p> </head> <body> <script> function func() { function EqualElements(array1, array2) { let EmpArr = []; for (let i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) { continue; } else { EmpArr.push(array1[i]); }; }; return EmpArr; }; const array1 = [10, 22, 30, 44, 50, 66, 70]; const array2 = [10, 33, 20, 44, 55, 60, 70]; document.getElementById("para").innerHTML = "Equal array elements (sequence dependent): " + EqualElements(array1, array2); }; </script> </body> </html>

As we can see in the output, 10, 44, and 70 are matching in both the arrays and they are in the same sequence. So, we pushed those elements into an empty array.

Example 2

In the following example below,

  • We have declared two arrays with elements in them. whenever the elements of both arrays are matching in the same sequence order, the count will be incrementing which is initially declared as 0.

<!DOCTYPE html> <html> <head> <title>Checking the equality of array elements (sequence dependent) in JavaScript</title> <button onClick="func()">Click!</button> <p id="para"></p> </head> <body> <script> const array1 = [10, 22, 30, 44, 50, 66, 70]; const array2 = [10, 33, 20, 44, 55, 60, 70]; function func() { function EqualElements(array1, array2) { let count = 0; var i = 0; while (i < array1.length) { if (array1[i] == array2[i]) { count++; } i++; } return count; }; document.getElementById("para").innerHTML = "Count of similar elements in sequence: " + EqualElements(array1, array2); }; </script> </body> </html>

In the output, the count got incremented whenever there is a match in both the arrays in the same sequence order.

Updated on: 08-Nov-2022

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements