Home > other >  check if array contains another array and its position in DART/Flutter
check if array contains another array and its position in DART/Flutter

Time:10-10

In dart language, I want to check if this array element=[1,1] exists in this array

list=[[0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3]] 

and give me the exact position if it does(3 in this case).

I tried indexOf but it doesn't work, always returns -1

CodePudding user response:

You can use indexWhere() to get the position of the item. And you should consider that you're trying to find a list in a list. Your expected list contains two items. So you can search it on the given list like this:

    var list = [
      [0, 3],
      [0, 4],
      [1, 0],
      [1, 1],
      [1, 2],
      [1, 3]
    ];

    var element = [1, 1];

    var index = list.indexWhere(
        (el) => el.first == element.first && el.last == element.last);

    print(index); // output will 3

Thanks to @pskink, you can also use listEquals method with importing the package.

    import 'package:flutter/foundation.dart';

///...

    var s = list.indexWhere((el) => listEquals(el, element));
    print(s); 

CodePudding user response:

You can use this function:

int isInList(List<List<dynamic>> list, List<dynamic> element) {
  for (int i = 0; i < list.length; i  ) {
    var e = list[i];
    if (e.length == element.length) {
      bool rejected = false;
      for (int j = 0; j < e.length; j  ) {
        if (e[j] != element[j]) {
          rejected = true;
        }
      }
      if (!rejected) {
        return i;
      }
    }
  }
  return -1;
}

the problem is you have a list of lists and indexOf won't compare elements of inner lists.

  • Related