KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility method to find all indexes in an array that equals a given value
PRODUCT: 4D | VERSION: 15 | PLATFORM: Mac & Win
Published On: October 13, 2015

Below is an example of finding all indexes of an array that equal a certain value.

//Find all indexes in a given array that equals a given value
//Method name: UTIL_FIND_ALL_IN_ARR
//
//$1 - Pointer to array to check
//$2 - Pointer to value to check for in array
//$3 - Pointer to contain resulting indexes
//$4 - (Optional) element to start searching

C_POINTER($arr;$1)
C_POINTER($val;$2)
C_POINTER($arrIndexes;$3)
C_LONGINT($start;$4)
C_LONGINT($i;$foundElem)

If (Count parameters>=3)

   $arr:=$1
   $val:=$2
   $arrIndexes:=$3

   If (Count parameters>=4)
      $start:=$4
   Else
      $start:=1
   End if

   $foundElem:=Find in array($arr->;$val->;$start)
   If ($foundElem#-1) & ($start<=Size of array($arr->)) //if val found
      APPEND TO ARRAY($arrIndexes->;$foundElem)
      UTIL_FIND_ALL_IN_ARR ($arr;$val;$arrIndexes;$foundElem+1)
   End if
End if


Example of using the method above to find the value "a" in the given array.
ARRAY LONGINT($resultArr;0)
ARRAY TEXT($arr;5)
$arr{1}:="a"
$arr{2}:="b"
$arr{3}:="a"
$arr{4}:="c"
$arr{5}:="d"
C_TEXT($val)
$val:="a"
UTIL_FIND_ALL_IN_ARR(->$arr;->$val;->$resultArr)
The resulting array returns elements 1 and 3.