OneBite.Dev - Coding blog in a bite size

Extract A Sub-Array From An Array In Dart

Code snippet for how to Extract A Sub-Array From An Array In Dart with sample and detail explanation

Managing arrays is a common scenario in any programming language. In this article, we will learn how to extract a sub array from an array in Dart, an object-oriented, class defined, single inheritance language using a concise and simple example.

Code snippet for Extracting A Sub Array From An Array In Dart

void main() {
  // Original Array
  List<int> array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  
  // Extract Sub Array
  List<int> subArray = array.sublist(2, 6);
  
  print(subArray);
}

When you run this code, your output should be: [3, 4, 5, 6]

Code Explanation for Extracting A Sub Array From An Array In Dart

In the provided code snippet, we begin by initializing and defining our original array, array, with a list of integers from 1 to 10. This is done using Dart’s List class.

List<int> array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Next, we want to extract a sub array from this array. This is performed by using Dart’s built-in sublist method.

List<int> subArray = array.sublist(2, 6);

The sublist method is called on array. It takes two parameters: the start index (inclusive) and the end index (exclusive). In our case, we wanted to begin our sub array at the third position (indexing in Dart starts at 0), and conclude it just before the seventh position, thus the parameters 2 and 6 are passed respectively.

Finally, the print function is called to output the subArray result.

print(subArray);

Our new extracted subArray contains the elements [3, 4, 5, 6] from our original array, showing just how simple it is to extract a sub-array from an array in Dart.

dart