How to iterate each value in 2 different array in dart/flutter?

527

Solution 1

You could use two for loops for this. Loop through option2 then inside it, loop through option1. Inside option1's for loop you can add it to your list.

void main() {
  final List<String> option1 = ["green", "yellow", "purple"];
  final List<int> option2 = [32, 33];
  List<List<dynamic>> myList=[];
  for (var item2 in option2) {
    for (var item1 in option1) {
      myList.add([item1, item2]);
    }
  }
  print(myList);
}

Output:

[[green, 32], [yellow, 32], [purple, 32], [green, 33], [yellow, 33], [purple, 33]]

Solution 2

void main(){
  
List<List> mergedArray=[]; 
  
List option1 = ["green", "yellow", "purple"];
List option2 = [32,33];
  
  for(int i =0;i<option1.length;i++){
    
    for(int j=0;j<option2.length;j++){
      mergedArray.add([option1[i],option2[j]]);
    }
  }
  
  mergedArray.forEach((val){
    print(val); //op:Your desired op
  });
}
Share:
527
patriece
Author by

patriece

Updated on December 24, 2022

Comments

  • patriece
    patriece over 1 year

    please help about logic in dart,

    i have 2 array:

    option1 = ["green", "yellow", "purple"
    option2 = [32,33]
    

    and i want to iterate them into this:

    mergedArray = [["green", 32], ["green", 33], ["yellow", 32], ["yellow",33], ["purple",32], ["purple",33]]
    

    help will be greatly appreciated, thankyou 🙏

  • CoderUni
    CoderUni over 3 years
    you don't have to forEach mergedArray but this is a nice answer.
  • UTKARSH Sharma
    UTKARSH Sharma over 3 years
    Yup just a cleaner one those who are unfamiliar with inbuilt function as such