How do I check if an array is equal to another array in JavaScript?
Rashid D
rashid d profile pic

To check if an array is equal to another array in JavaScript, you can compare their lengths and elements. Here's a step-by-step guide on how to achieve this: 1. Get the arrays you want to compare:

1
2
3
4

   const array1 = [1, 2, 3];
   const array2 = [1, 2, 3];
   

Replace[1, 2, 3] with the actual arrays you want to compare. 2. Compare the lengths of the arrays: Start by checking if the lengths of both arrays are equal. If they have different lengths, they are not equal, and you can returnfalse.

1
2
3
4
5

   if (array1.length !== array2.length) {
     return false;
   }
   

3. Compare the elements of the arrays: Iterate over the arrays and compare the corresponding elements. If any pair of elements differs, the arrays are not equal, and you can returnfalse. Otherwise, if all pairs of elements match, the arrays are equal.

1
2
3
4
5
6
7

   for (let i = 0; i < array1.length; i++) {
     if (array1[i] !== array2[i]) {
       return false;
     }
   }
   

4. Return the result: If the loop completes without finding any unequal elements, the arrays are equal, and you can returntrue.

1
2
3

   return true;
   

Putting it all together, the complete code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function areArraysEqual(array1, array2) {
  if (array1.length !== array2.length) {
    return false;
  }

  for (let i = 0; i < array1.length; i++) {
    if (array1[i] !== array2[i]) {
      return false;
    }
  }

  return true;
}

const array1 = [1, 2, 3];
const array2 = [1, 2, 3];
console.log(areArraysEqual(array1, array2));  // Output: true

By following these steps, you can check if two arrays are equal in JavaScript. Keep in mind that this comparison method assumes the arrays have the same order of elements and compares the elements using strict equality (===). If you need to compare arrays with different orders or consider nested arrays, you may need to employ more advanced comparison techniques or utility libraries.