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:
- Variable Declaration:
We declare two variables,
inputArray
, which is the array to be split, andchunkSize
, 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;
- 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 = [];
- The loop for creating chunks:
The loop runs from the start of
inputArray
towards the end, incrementing by the definedchunkSize
in each iteration.
for (int i=0; i<inputArray.length; i+=chunkSize)
- Creating Sublists:
In each iteration, the
sublist
method is used to create sublists frominputArray
of sizechunkSize
. These sublists are then added tochunks
.
chunks.add(inputArray.sublist(i, i+chunkSize > inputArray.length ? inputArray.length : i+chunkSize));
- 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.