I have this list [null, 3, 5, null]
and I want to join the values in-between null
s and put it into the same list
For example:
[null, 3, 5, null] into [null, 35, null]
I made this one extension that groups all the values between two null
s
extension GroupByNull<T> on List<T> {
List<List<T>> groupByNull() {
final groupedList = <List<T>>[];
var list = this;
for (var i = 0; i < list.length; i++) {
if (list[i] == null) {
if (i > 0) {
groupedList.add(list.sublist(0, i));
}
list = list.sublist(i + 1);
i = 0;
}
}
if (list.isNotEmpty) {
groupedList.add(list);
}
return groupedList;
}
}
Which returns [[3, 5]]
for [null, 3, 5, null]
... But I want it to be joined together and added to the original list in the same index
How can I solve this... thank you.
Note that you can't operate on an arbitrary List<T>
because there's no general way to combine two elements of some arbitrary type T
. What you want could make sense for List<int?>
or maybe List<String?>
. (Or maybe it could work on an arbitrary List<T>
input if you want a List<String?>
output.)
Assuming that you want to operate on List<int?>
, then basically as you iterate over your input list, keep track of your current accumulated value. If you encounter null
, add the current value (if any) to your output List
along with the null
. Don't forget to add the current accumulated value (if any) when you're done iterating in case there isn't a final null
element.
extension GroupByNull on List<int?> {
List<int?> groupByNull() {
var result = <int?>[];
int? currentValue;
for (var element in this) {
if (element != null) {
currentValue = (currentValue ?? 0) * 10 + element;
} else {
if (currentValue != null) {
result.add(currentValue);
currentValue = null;
}
result.add(currentValue);
}
}
if (currentValue != null) {
result.add(currentValue);
}
return result;
}
}
void main() {
print([null, 3, 5, null].groupByNull()); // Prints: [null, 35, null]
print([3, 5, null].groupByNull()); // Prints: [35, null]
print([3, 5, null, null].groupByNull()); // Prints: [35, null, null]
print([null, 3, 5].groupByNull()); // Prints: [null, 35]
print([null, null, 3, 5].groupByNull()); // Prints: [null, null, 35]
print([null, 0, 0, 0, null].groupByNull()); // Prints: [null, 0, null]
print([null, 1, 2, null, 3, 4, null]
.groupByNull()); // Prints: [null, 12, null, 34, null]
print([null].groupByNull()); // Prints: [null]
print([null, null].groupByNull()); // Prints: [null, null]}
}