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.
2
Answers
You can use this solution.
Note that you can’t operate on an arbitrary
List<T>
because there’s no general way to combine two elements of some arbitrary typeT
. What you want could make sense forList<int?>
or maybeList<String?>
. (Or maybe it could work on an arbitraryList<T>
input if you want aList<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 encounternull
, add the current value (if any) to your outputList
along with thenull
. Don’t forget to add the current accumulated value (if any) when you’re done iterating in case there isn’t a finalnull
element.