As a developer, you often need to know whether a specified item already exists in a collection, or to find all the items corresponding to particular criteria. 4D collection methods offer many different ways to look up specific items.
This article is part of a series demonstrating how to manipulate collections with the methods added in 4D v16 R6. To learn even more, download our database demo, which includes 12 different examples to show all you can do with collection methods!
Database example: Manage collections
HOW To find items in a collection?
Now, let’s look at the different ways 4D provides for finding items in a collection. First, we start by building a collection as follows:
$col:=New collection(New object("City";"Paris";"Weather";1))
$col.push(New object("City";"New-York";"Weather";-10))
$col.push(New object("City";"Tokyo";"Weather";-5))
$col.push(New object("City";"Miami";"Weather";15))
Use “some” or “every” methods
To determine if at least one value of your collection is greater than 0, you can use the some method:
$b:=$col.some("WeatherGreaterThan0") // true
where WeatherGreaterThan0 is a project method, used as a call back, as follows:
$1.result:=$1.value.Weather>0
Now, if you want to know if all of the elements in your collection match with a custom test, just use every:
$b:=$col.every("WeatherGreaterThan0") // false
Note that the same callback method could also be used for many other cases, as a kind of generic method.
filter a collection
You can filter a collection according to a call back method results with the filter method.
In the same way as the examples above, if you want to create a collection with all values greater than 0 from another collection:
$colNew:=$col.filter("WeatherGreaterThan0")
// [{City:Paris,Weather:1},{City:Miami,Weather:15}]
find the first element matching a criteria
If you’re searching for the first element of a collection that matches with a specified project method, just use find as a call back method:
$o:=$col.find("WeatherGreaterThan0") // {City:Paris,Weather:1}
In the same way, if you’re searching the index and not the element itself, use findIndex:
$index:=$col.findIndex("WeatherGreaterThan0")
// $i=0 (first index of collection)
Get index of a searched element
Finally, you can use the indexOf and lastIndexOf methods to search for an expression among collection elements and return the index of the first / last occurrence found:
$col2:=New collection(1;2;"Henry";"Albert";"Henry";6;4;"Henry";5)
$i:=$col2.indexOf("Henry") //$i=2 index of the first occurrence
$i:=$col2.lastIndexOf("Henry") //$i=7 index of the last occurrence