Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find the index of item even there is duplication in Dart

I’m really confused on how I’m gonna find the index of item in array where there’s a lot of duplicated words.

List<String> _words = "the quick brown fox jumps over the lazy dog".split(" ");

now I want to get the all the index in word "the" programmatically.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I expect a result of

List indexOfWords = _words.indexOfAll("the");
print(indexOfWords);

// [0, 6]

>Solution :

You can define indexOfAll as an extension method. I would implement it like this:

extension ListExtension<T> on List<T> {
  List<int> indexOfAll(T item) => [
        for (int i = 0; i < length; i++)
          if (this[i] == item) i,
      ];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading