Splitting integer array into multiple chunks in different length in Dart

Viewed 465
List<int> mainList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

List<int> chukLengths= [2,4,4,4,2]

Expected Result:

[[1,2],[3,4,5,6],[7,8,9,10],[11,12,13,14],[15,16]]

I wanna split mainList to 5 chunks with mentioned chunkLength. How to resolve it in Dart?

1 Answers

You can iterate over the array of your chunks and slice off necessary chunks off the main array. Each iteration your get the chunk itself by using sublist() and then you delete the chunk from the initial array using removeRange()

Here is the code:

List<int> mainList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
List<int> chukLengths= [2,4,4,4,2];

List<List<int>> splitIntoChunks(List<int> list, List<int> chunks) {
  List<List<int>> result = [];
  

  for (int chunk in chunks) {
    result.add(list.sublist(0, chunk));
    list.removeRange(0, chunk);
  }
  
  return result;
}

void main() {
  print(splitIntoChunks(mainList, chukLengths)); // [[1, 2], [3, 4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14], [15, 16]]
}

Related