OneBite.Dev - Coding blog in a bite size

Split An Array Into Smaller Arrays In Dart

Code snippet for how to Split An Array Into Smaller Arrays In Dart with sample and detail explanation

Dart is an object-oriented, class-defined, garbage-collected language developed by Google. It’s known for its capabilities to build web, server, desktop, and mobile applications. One key functionality we’ll examine in this article is how you can split an array into smaller arrays in Dart.

Code snippet: Splitting an Array into Smaller Arrays

Here is an example of how to split an array into smaller arrays in Dart.

void main() {
  var inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var chunkSize = 3;
  
  var chunks = [];
  for (int i=0; i<inputArray.length; i+=chunkSize)
    chunks.add(inputArray.sublist(i, i+chunkSize > inputArray.length ? inputArray.length : i+chunkSize));
  
  print(chunks);
}

When you run this program, it splits the inputArray into smaller arrays, each with a maximum size of chunkSize.

Code Explanation: Splitting an Array into Smaller Arrays

Step by Step, let’s dissect the code snippet:

  1. Variable Declaration: We declare two variables, inputArray, which is the array to be split, and chunkSize, which specifies the size of the smaller arrays to be made.
var inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var chunkSize = 3;
  1. Creation of the list to hold the chunks: We declare an empty list, chunks, which will hold all the smaller arrays after the input array has been split.
var chunks = [];
  1. The loop for creating chunks: The loop runs from the start of inputArray towards the end, incrementing by the defined chunkSize in each iteration.
for (int i=0; i<inputArray.length; i+=chunkSize)
  1. Creating Sublists: In each iteration, the sublist method is used to create sublists from inputArray of size chunkSize. These sublists are then added to chunks.
chunks.add(inputArray.sublist(i, i+chunkSize > inputArray.length ? inputArray.length : i+chunkSize));
  1. Printing Chunks: Finally, we print all the smaller arrays created from the input array.
print(chunks);

The result of this program will be [[1, 2, 3], [4, 5, 6], [7, 8, 9]], demonstrating the splitting of the original inputArray into smaller arrays of size specified by chunkSize.

With this easy, step-by-step guide, splitting an array into smaller arrays in Dart should be a straightforward process.

dart