Home > Blockchain >  Flutter/Dart: Remove Elements from List based on index or mask
Flutter/Dart: Remove Elements from List based on index or mask

Time:03-14

let's assume I have two lists values and mask:

List<int> values = [2,8,3,5,1];
List<bool> mask = [true, false, true, true, false];
// desired outcome: [2,3,5]

What is the shortest/best/most elegant way to filter the values based on the value of the mask? For example in JavaScript I could do:

values.filter((_, i) => mask[i]);
// yields: [2,3,5]

Is there something similar in Dart?

CodePudding user response:

I figured this will work. If someone has another idea, I would be thankful :)

List.generate(values.length, (i) => i).where((i) => mask[i]).map((i) => values[i]).toList();

CodePudding user response:

I would use asMap to solve this, the key is then the index and the value the original value.

values.asMap().entries.where((e) => mask[e.key]).map((e) => e.value).toList(); ```
  • Related