1

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 🙏

0

2 Answers 2

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]]
Sign up to request clarification or add additional context in comments.

Comments

1
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
  });
}

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.