flattenDepth function

List flattenDepth(
  1. List list, [
  2. int depth = 1
])

Recursively flatten list up to depth times.

  • @param {List} list The list to flatten.
  • @param {int} depth=1 The maximum recursion depth.
  • @returns {List} Returns the new flattened list.

@example

var list = [1, [2, [3, [4]], 5]];

flattenDepth(list, 1);
// => [1, 2, [3, [4]], 5]

flattenDepth(list, 2);
// => [1, 2, 3, [4], 5]

Implementation

List flattenDepth(List list, [int depth = 1]) {
  if (depth < 1) {
    return List.from(list);
  }

  final result = [];

  void flatten(List items, int currentDepth) {
    for (var item in items) {
      if (item is List && currentDepth > 0) {
        flatten(item, currentDepth - 1);
      } else {
        result.add(item);
      }
    }
  }

  flatten(list, depth);
  return result;
}