2

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

3
  • 1
    final b = [1, 1]; final index = list.indexWhere((a) => listEquals(a, b)); print(index); Commented Oct 10, 2021 at 9:48
  • sure, your welcome Commented Oct 10, 2021 at 9:58
  • what if b = [1,1] and list = [0,1,2,3,4,5,6,7,1,1]? what should i use? Commented Nov 25, 2021 at 3:09

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.