simc / dartx

Superpowers for Dart. Collection of useful static extension methods.
https://pub.dev/packages/dartx
Apache License 2.0
1.08k stars 88 forks source link

Feature Request "IndicesWhere" #166

Closed gnudles closed 1 year ago

gnudles commented 1 year ago

On List, add extension of "IndicesWhere" that returns iterable of the indices in the array where a certain condition met.

ilovelinux commented 1 year ago

Could you please show us some use cases where you need only the indices of the array?

If you want both indices and values you can mix asMap with where. Example:

final listOfNumbers = [1, 2, 3, 4];
final evenNumbers = listOfNumbers.asMap().entries.where((entry) => entry.value % 2 == 0);
// [MapEntry(1: 2), MapEntry(3: 4)]

evenNumbers will be an iterable with MapEntries. Each MapEntry will have a key, which is the array index of that value, and a value, which is the corresponding value of that index in the array.

passsy commented 1 year ago

What you're looking for is filterIndexed which already exists

final list = ['a', 'bb', 'ccc'].filterIndexed((element, index) => index.isEven);
print(list); // (a, ccc)