KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Finding Index in Collection with Formula
PRODUCT: 4D | VERSION: 19 R 6 | PLATFORM: Mac & Win
Published On: January 9, 2023

Starting with 4D v19 R6, 4D allows you to use a formula to define a callback in the collection member functions. For example, you can now use formula as callback in the members method, .findIndex()

.findIndex() function returns the index, in the collection, of the first value for which formula, applied on each element, returns true.

Note: By default, .findIndex() searches in the whole collection.
Optionally, you can pass in startFrom the index of element for which to start the search.

Below is an example that utilizes .findIndex()

var $newCol : Collection
var $val1; $val2 : Integer
$newCol:=New collection
$newCol.push(New object("name"; "name1"; "number"; 12345)) // 0
$newCol.push(New object("name"; "name2"; "number"; 67890)) // 1
$newCol.push(New object("name"; "name3"; "number"; 65432)) // 2
$newCol.push(New object("name"; "name4"; "number"; 98765)) // 3
$newCol.push(New object("name"; "name3"; "number"; 0)) // 4

$val1:=$newCol.findIndex(Formula($1.value.name=$2); "name3") // $val1=2
$val2:=$newCol.findIndex($val1+1; Formula($1.value.name=$2); "name3") // $val2=4