Home > Enterprise >  find the index of item even there is duplication in Dart
find the index of item even there is duplication in Dart

Time:12-30

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.


I expect a result of
List indexOfWords = _words.indexOfAll("the");
print(indexOfWords);

// [0, 6]

CodePudding user response:

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,
      ];
}

CodePudding user response:

You can create an extension method. like this:

extension Occurrences on List {
  List<int> indexOfAll(String pattern) {
    List<int> indexes = [];
    for (int i = 0; i < this.length; i  ) {
      if (this[i] == pattern) {
        indexes.add(i);
      }
    }
    return indexes; 
  }
}

then you can use it as function on your list

print(_words.indexOfAll("the")); // [0, 6]

CodePudding user response:

I don't know if there is a direct solution for this job. To solve this problem I developed a function called GetIndexes() and it works successfully.

void main()
{
   String text = "the quick brown fox jumps over the lazy dog";
   var split = ' ';
   List<int> indexes = [];
   List<String> words;
   
   words = text.split(split);
   GetIndexes(text, split, indexes);
   print(words);
   print(indexes);
}

void GetIndexes(String text, var split, List<int> indexes)
{
    int index = 0;
    
    for(int i=0 ; i<text.length;   i)
    {
        if(text[i] == split)
        {
            indexes.insert(index, i);
              index;
        }
    }
}

This example prints the following output to the console:

[the, quick, brown, fox, jumps, over, the, lazy, dog]
[3, 9, 15, 19, 25, 30, 34, 39]
  •  Tags:  
  • dart
  • Related