Insert or remove elements from a collection

Automatically translated from English

Adding and/or removing elements to and from collections are common programming tasks that developers often encounter. 4D v16 R6 provides over 40 collection methods, including methods specifically dedicated to the addition and removal of elements in a collection. With these methods, you can easily create a stack (FIFO) or queue (LIFO), add new elements at any position, and much more…

This article is part of a series demonstrating how to manipulate collections using the methods added in 4D v16 R6. To learn even more, download our database example, which includes 12 different examples to show all you can do with collection methods!

Database example: Manage collections

Manage first and last elements

Adding a value at the beginning of a collection or removing the first element is easy, thanks to the shift and unshift methods.

$col:=New collection("a";"b")
// Insert a new value at the beginning of $col
$col.unshift("c") // $col=["c","a","b"]
// Read and remove the first element of $col
$r:=$col.shift()
// $r="c"
// $col=["a","b"]

Similarly, the push method can be used to add an element at the end of a collection and the pop method can remove the last element.$col:=New collection("a";"b")
// Insert a new value at the end of the $col collection
$col.push("c") // $col=["a","b","c"]
// Read and remove the last element of $col
$r:=$col.pop()
// $r="c"
// $col=["a","b"]

Insert OR remove any element

Of course, it’s also possible to add or remove an element anywhere in the collection with the insert and remove methods:

$col:=New collection("a";"b")
// Insert a new value at a specific position in $col
$col.insert(1;"c") // $col=["a","c","b"]
// Remove the second element of $col
$col.remove(1)
// $col=["a","b"]

The clear method removes all the elements in a collection:

$col:=New collection("a";"b";"c";"d";"e")
$col.clear() // $col=[]

Fill or resize a collection

You can replace all the values in a collection by using the fill method.

$col:=New collection("a";"b";"c";"d";"e")
// Reset all the values of $col to ""
$col.fill("") // $col=["","","","",""]

And you can resize a collection with the resize method:

$col:=New collection("a";"b")
$col.resize(5;"") // $col=[a,b,"","",""]

 

Fabrice Mainguené

• Product Owner •

Fabrice Mainguené joined 4D Program team in November, 2016. As a Product Owner, he is in charge of writing the user stories then translating it to functional specifications. His role is also to make sure that the feature implementation delivered is meeting the customer need.

After obtaining a Bachelor degree in Computer Science at CNAM, Fabrice joined a small software publishing company as a Windev developer. Then he worked for different companies in industry and trade areas as a Windev and web developer as well as technical advisor on new features.