OneBite.Dev - Coding blog in a bite size

Check If Two Arrays Are Equal In Dart

Code snippet for how to Check If Two Arrays Are Equal In Dart with sample and detail explanation

Determining whether two arrays are identical in Dart is a common challenge for many developers, particularly for beginners. This article provides a simple tutorial on how to check if two arrays are equal in Dart.

Code Snippet: Checking Array Equality in Dart

void main() { 
  List array1 = [1,2,3,4,5]; 
  List array2 = [1,2,3,4,5]; 

  print(arrayEquality(array1,array2)); 
} 

bool arrayEquality(List array1, List array2) { 
  bool isEqual = true; 

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

Code Explanation: Checking Array Equality in Dart

This Dart code is designed to check whether two arrays (array1 and array2) are equal or not. Here’s how it works:

  1. At the very start of the ‘main’ function, we define two arrays (array1 and array2) with identical elements.

  2. Next, we call print() function with ‘arrayEquality’ function as an argument where we pass both arrays as parameters. This will print the result of this function.

  3. Now, let’s dive into the ‘arrayEquality’ function. This function takes two parameters (array1 and array2) and checks if they are equal. It will return ‘true’ if they both are equal and ‘false’ otherwise.

  4. At the beginning of the function, a boolean variable ‘isEqual’ is declared to keep track of whether the two arrays are equal or not.

  5. Then, it checks if the length of both arrays is equal. If the lengths are not equal, it simply returns ‘false’.

  6. If the length is the same, then it enters a for loop where the elements of both arrays are compared one by one. If at any point, the elements are not equal, the ‘isEqual’ variable is set to ‘false’ and the loop breaks.

  7. After the loop finishes, the function returns the value of ‘isEqual’. If all elements are equal (i.e., no different elements were found in the loop), ‘isEqual’ remains ‘true’, which means the two arrays are equal. Otherwise, it returns ‘false’.

Therefore, using this code snippet, one can easily check whether two arrays are equal in Dart.

dart