Home > Net >  Merge Array List Flutter and saperate it
Merge Array List Flutter and saperate it

Time:04-25

my List

list1 = [1, 2, 3]

list2 = [A, B, C]

I wanted the combined output of:

[1, A | 2, B | 3, C]

help me to figure it out.

CodePudding user response:

You can try this.

void main() {
 List list1 = [1, 2, 3];

 List list2 = ["A", "B", "C"];
 List list3 = [];
  
  
  for (var i = 0; i <= list1.length; i  ) {
    if (i == 0) {
      list3.add(list1[i]);
    } else if (i == list1.length) {
      list3.add("${list2[i - 1 ]}");
    } else {
       list3.add("${list2[i - 1]} | ${list1[i]}");
    }
  }
  print(list3);  // [1, A | 2, B | 3, C]
  
}

CodePudding user response:

Is something like this what you want?

import 'package:collection/collection.dart';

void main() {
  var a = [1,2,3];
  var b = ["A","B","C"];
  List<String> c = [];
  for (final pairs in IterableZip([a, b])) {
    c.add(pairs[0].toString()   pairs[1].toString());
  }
  print(c); //prints [1A, 2B, 3C]
}

CodePudding user response:

I'm guessing this is what you are looking for

So, just for some clarification about the answer, each list is being looped and added to another list one after another till there are no elements left.

A = [1,2,3]
B = [A,B,C]

loop each list

C = [1]
A[0]
C = [1,A]
B[0]
C = [1,A,2]
A[1]
C = [1,A,2,B]
B[1]
C = [1,A,2,B,3]
A[2]
C = [1,A,2,B,3,C]
B[2]

This will work even for uneven lists. Hope it helps.

  • Related