Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Dart's List's "some" method is called? Method checking if at least one element passes a test

On JavaScript arrays, there is the some method:

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

I think there must be a similar method on the Dart lists, too, but I just can't seem to find it anywhere on the internet or in the List docs.

I got used to Dart having different names for some of the methods, so I always spend like 5 minutes until I remember that JavaScript's find is called where, and so on. However, I can't seem to find some's equivalent.

like image 679
Vince Varga Avatar asked Feb 03 '20 16:02

Vince Varga


People also ask

How do you check if an element is in a list Dart?

The contains() method is used to check if an element occurs in a list. This method takes one parameter and returns a boolean value indicating whether or not that item is found in the list.

Where is the method in Flutter?

where method Null safety. Returns a new lazy Iterable with all elements that satisfy the predicate test . The matching elements have the same order in the returned iterable as they have in iterator. This method returns a view of the mapped elements.

How many types of Dart lists are there?

There are two types of list: Fixed length list. Growable list.

How do you check index in Flutter?

You can use array. asMap(). containsKey(index) to check if the Key index exists or not in Array List. In this way, you can check if Array List has a Key index or value or not in Dart or Flutter.


1 Answers

Huh! The problem was that the equivalent of JavaScript's some method is a method on the Iterable class and not on the List. The List class implements the Iterable, though, so I could have found it earlier, but I guess I was lost in all those method descriptions.

Dart's equivalent of the some method is called: any:

Iterable<E> bool any(bool test(E element))

Checks whether any element of this iterable satisfies test.

Checks every element in iteration order, and returns true if any of them make test return true, otherwise returns false.

Example usage:

// The list in which we want to check if there is an item that passes a certain test.
List<String> haystack = [
  // It contains some elements...
];
// Just to be explicit in this example, you don't really need it
typedef TestFunc = bool Function(String);
// The test. Just some function that takes an element and returns boolean.
TestFunc isNeedle = (String v) => v.toLowerCase().contains('needle');

bool gotNeedle = haystack.any(isNeedle);
like image 73
Vince Varga Avatar answered Sep 20 '22 19:09

Vince Varga