Suppose, I have a list: firstList = ["Travel", "Shopping", "Transport"];
another list: secondList = ["Travel", "Shopping", "Shopping", "Travel", "Transport", "Transport", "Travel", "Travel"]
I need to find the index of all the elements from the secondList that contains: "Travel"
Here in secondList "Travel" is present in index 0, 3, 6, and 7
Now, I have a 3rd List containing the index of the element, here "Travel".
indexList = [0, 3, 6, 7] // Since index 0, 3, 6, and 7 only contains the element "Travel".
Below is my program:
for (int i = 0; i < firstList.length; i++) {
    for (int j = 0; j < secondList.length; j++) {
           
      indexList.add(secondList.indexOf(firstList[i]));
         }
    } 
This is not working as I am getting output like this:
[0, 0, 0, 0, 0, 0, 0, 0, 0]
Seems like it stuck on the first index itself.
The "Travel", here is an example, it should be matching dynamically such, firstList[i] or any other element not just "Travel" as hardcoded. Such as if I have selected firstList[i] then find the index of the same element in the secondList[].
Please help me to identify the cause. I am new to programming.
Try this:
main() {
  var firstList = ["Travel", "Shopping", "Transport"];
  var secondList = [
    "Travel",
    "Shopping",
    "Shopping",
    "Travel",
    "Transport",
    "Transport",
    "Travel",
    "Travel"
  ];
  var thirdList = [];
  for (var i = 0; i < secondList.length; i++) {
    if (secondList[i] == "Travel") {
      thirdList.add(i);
    }
  }
  print(thirdList);
}
EDIT: For it to work for every item in firstList
Try this:
main() {
  var firstList = ["Travel", "Shopping", "Transport"];
  var secondList = [
    "Travel",
    "Shopping",
    "Shopping",
    "Travel",
    "Transport",
    "Transport",
    "Travel",
    "Travel"
  ];
  var thirdList = [];
  for (var i = 0; i < firstList.length; i++) {
    var sublist = [];
    for (var j = 0; j < secondList.length; j++) {
      if (secondList[j] == firstList[i]) {
        sublist.add(j);
      }
    }
    thirdList.add(sublist);
  }
  print(thirdList); // [[0, 3, 6, 7], [1, 2], [4, 5]]
}
  List firstList = ["Travel", "Shopping", "Transport"];
  List secondList = ["Travel", "Shopping", "Shopping", "Travel", "Transport", "Transport", "Travel", "Travel"];
  List indexList = [];
  getElement() {
    for (int i = 0; i <= secondList.length; i++) {
      if (secondList[i] == "Travel") {
        indexList.add(i);
      }
    }
    print(indexList);
  }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With