KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Using .remove() to Remove Multiple Elements at a Time
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: December 27, 2019

The .remove() member function is particulary useful when wanting to remove collection elements based on their index position. When trying to remove multiple elements in different positions at a time, the code example below shows how it can be done.

Let's say we want to remove the elements from collection $c at positions 0, 3, and 6. The corresponding elements to be removed would be "zero", "three", and "six". In the example, another collection ($position) is created to contain the index positions we want to remove from the target collection ($c). Next, we will loop through the collection of index positions and remove each element in that position from collection $c.

Note: Be careful with the order of removing elements from a collection. ($position:=$position.orderBy(ck descending) is used to sort the collection of indexes in descending order, enabling the removal of elements starting from the last index to the first index (ie. removes element in position 6, 3, then 0). This is necessary becasue if position 0 were to be removed first, it would affect the position of each element after 0. The element in position 1 would be shifted to position 0 and so forth. Therefore, the elements in position 3 and 6 would not be in their original position.

C_COLLECTION($c;$position)
$c:=New collection("zero";"one";"two";"three";"four";"five";"six")
$position:=New collection(0;3;6)
$position:=$position.orderBy(ck descending)

For ($i;0;$position.length-1)
   $c:=$c.remove($position[$i])
End for


The result of collection $c is ("one";"two";"four";"five").