ScriptForge.Array service (SF_Array)

Contingut

# Servei ScriptForge.Array

Provides a collection of methods for manipulating and transforming arrays of one dimension (vectors) and arrays of two dimensions (matrices). This includes set operations, sorting, importing from and exporting to text files.

No es poden utilitzar matrius amb més de dues dimensions amb els mètodes d’aquest servei, l'única excepció és el mètode CountDims que accepta matrius amb qualsevol nombre de dimensions

Els elements de matriu poden contenir qualsevol tipus de valor, incloent (sub) matrius.

One-dimensional arrays containing only one-dimensional subarrays are called below data arrays. They are particularly suited for exchanges of tabular data with Python scripts and Calc sheets.

## Invocació del servei

Abans d'utilitzar el servei Array, la biblioteca ScriptForge s'ha de carregar utilitzant:

        GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

Carregar la biblioteca crearà l'objecte SF_Array, que es pot utilitzar per a cridar els mètodes del servei Array.

Els fragments de codi següents mostren diverses maneres de cridar als mètodes del servei Matriu (el mètode Append s'utilitza com exemple):

        Dim arr : arr = Array(1, 2, 3)
        arr = SF_Array.Append(arr, 4)

        Dim arr : arr = Array(1, 2, 3)
        Dim svc : svc = SF_Array
        arr = svc.Append(arr, 4)

        Dim arr : arr = Array(1, 2, 3)
        Dim svc : svc = CreateScriptService("Array")
        arr = svc.Append(arr, 4)

Because Python has built-in list and tuple support, most of the methods in the Array service are available for Basic scripts only. The only exception is ImportFromCSVFile which is supported in both Basic and Python.

Llista de mètodes del servei Array
Append AppendColumn AppendRow Contains ConvertFromDataArray ConvertToDataArray ConvertToDictionary ConvertToRange Copy CountDims Difference ExportToTextFile | ExtractColumn ExtractRow Flatten ImportFromCSVFile IndexOf Insert InsertSorted Intersection Join2D Prepend PrependColumn PrependRow | RangeInit Reverse Shuffle Slice Sort SortColumns SortRows Transpose TrimArray Union Unique

El primer argument de la majoria de mètodes és l’objecte matriu a considerar. Sempre es passa per referència i es deixa sense canvis. Mètodes com ara Append, Prepend, etc. retornen un nou objecte array després de la seva execució.

## Append

Afegeix els elements llistats com a arguments al final de la matriu d'entrada.

### Sintaxi:

svc.Append(array_1d: any[0..*], arg0: any, [arg1: any] ...): any[0..*]

### Paràmetres:

array_1d: The pre-existing array, may be empty.

arg0, arg1, ...: Items that will be appended to array_1d.

### Exemple:

        Dim a As Variant
        a = SF_Array.Append(Array(1, 2, 3), 4, 5)
            ' (1, 2, 3, 4, 5)

## AppendColumn

Afegeix una nova columna a la part dreta d'una matriu bidimensional. La matriu resultant té els mateixos límits inferiors que la matriu bidimensional inicial.

### Sintaxi:

svc.AppendColumn(array_2d: any[0..*, 0..*], column: any[0..*]): any[0..*, 0..*]

### Paràmetres:

array_2d: The pre-existing array, may be empty. If that array has only one dimension, it is considered as the first column of the resulting two-dimensional array.

column: A 1-dimensional array with as many items as there are rows in array_2d.

### Exemple:

        Dim a As Variant, b As variant
        a = SF_Array.AppendColumn(Array(1, 2, 3), Array(4, 5, 6))
            ' ((1, 4), (2, 5), (3, 6))
        b = SF_Array.AppendColumn(a, Array(7, 8, 9))
            ' ((1, 4, 7), (2, 5, 8), (3, 6, 9))
        c = SF_Array.AppendColumn(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(0, i) ≡ i

## AppendRow

Afegeix a la part inferior d'una matriu de dues dimensions una fila nova. La matriu resultant té els mateixos límits inferiors que la matriu inicial de dues dimensions.

### Sintaxi:

svc.AppendRow(array_2d: any[0..*, 0..*], row: any[0..*]): any[0..*, 0..*])

### Paràmetres:

array_2d: The pre-existing array, may be empty. If that array has 1 dimension, it is considered as the first row of the resulting 2 dimension array.

row: A 1-dimensional array with as many items as there are columns in array_2d.

### Exemple:

        Dim a As Variant, b As variant
        a = SF_Array.AppendRow(Array(1, 2, 3), Array(4, 5, 6))
            '  ((1, 2, 3), (4, 5, 6))
        b = SF_Array..AppendRow(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(i, 0) ≡ i

## Contains

Comproveu si una matriu d'una dimensió conté un nombre, un text o una data determinats. La comparació pot distingir entre majúscules i minúscules.
Les matrius d'entrada ordenades s'han d'omplir de manera homogènia, és a dir, tots els elements han de ser escalars del mateix tipus (elements Buits i Nuls estan prohibits).
El resultat del mètode és imprevisible quan la matriu s'assenyala com a ordenada i, en realitat, no ho està.
Una cerca binària es fa quan s’ordena la matriu, en cas contrari, simplement s’escaneja de dalt a baix ii els elements Buits i Nuls s'ignoren.

### Sintaxi:

svc.Contains(array_1d: any[0..*], tofind: any, casesensitive: bool = False, sortorder: str = ""): bool

### Paràmetres:

array_1d: The array to scan.

tofind: A number, a date or a string to find.

casesensitive: Only for string comparisons (Default = False).

sortorder: It can be either "ASC", "DESC" or "" (not sorted). The default value is "".

### Exemple:

        Dim a As Variant
        a = SF_Array.Contains(Array("A","B","c","D"), "C", SortOrder := "ASC") ' True
        SF_Array.Contains(Array("A","B","c","D"), "C", CaseSensitive := True) ' False

## ConvertFromDataArray

Convert a data array to a Basic array.
A data array is an array of subarrays. On request, the individual output items are reduced to strings or doubles only.

The method returns a scalar, a zero-based 1D array or a zero-based 2D array.
The number of columns in the resulting 2D array is equal to the number of items in the 1st subarray. If next subarrays have a different size, next rows will be complemented with the fillvalue argument or truncated.

### Sintaxi:

svc.ConvertFromDataArray(dataarray: any[any[0..*], ...], isrange: bool = False, fillvalue: str = ''): any[0..*, 0..*]

### Paràmetres:

dataarray: An array of subarrays. Array and subarrays must be zero-based.
Typically a data array is either output by

- el mètode session.ExecuteCalcFunction()

- a Python script returning a tuple of tuples

- el mètode getDataArray() de la interfície com.sun.star.sheet.XCellRangeData

isrange: When True (default = False), the items are converted to strings or doubles.

fillvalue: How to replace missing items. Default = the empty string.

### Exemple:

        Dim dataarray As Variant, array2D As Variant
        dataarray = Array(Array("Col1", "Col2", "Col3"), Array(10, 20, 30))
        array2D = SF_Array.ConvertFromDataArray(dataarray)
        MsgBox array2D(1, 2) ' 30

## ConvertToDataArray

Create a data array from a scalar, a 1D array or a 2D array.
A data array is a zero-based array of zero-based subarrays. On request, the individual output items are reduced to strings or doubles only.

The returned data array is typically used as

- a tuple of (sub)tuples passed to a Python script

- argument of the setDataArray() method from the com.sun.star.sheet.XCellRangeData interface

### Sintaxi:

svc.ConvertToDataArray(data: any[0..*, 0..*], isrange: bool = False, rows: int = 0, columns: int = 0): any[any[0..*], ...]

### Paràmetres:

data: The input scalar, 1D or 2D array.

isrange: When True (default = False), the array items are stored as (possibly empty) strings or doubles only into the data array.

rows, columns: The number of rows or columns of the returned data array. When they exceed the limits of data, fill with zero-length strings. If rows = 1 and the input array is a vector, the data array is aligned horizontally (by default, vectors are aligned vertically). When absent, the size of the output is determined by the input array.

### Exemple:

        Dim data As Variant, dataarray As Variant
        data = Array(1, 2, 3)
        data = SF_Array.AppendRow(data, Array(4, 5, 6))
        dataarray = SF_Array.ConvertToDataArray(data)
        MsgBox dataarray(1)(2) ' 6

## ConvertToDictionary

Emmagatzemeu el contingut d'una matriu de 2 columnes en un objecte ScriptForge.Dictionary.
La clau s’extreurà de la primera columna, l’element de la segona.

### Sintaxi:

svc.ConvertToDictionary(array_2d: any[0..*, 0..1]): obj

### Paràmetres:

array_2d: Data to be converted into a ScriptForge.Dictionary object.

- The first column must contain exclusively strings with a length greater than zero, in any order. These values will be used as labels in the dictionary.

- The second column contains the data that will be associated to the corresponding label in the dictionary.

### Exemple:

        Dim a As Variant, b As Variant
        a = SF_Array.AppendColumn(Array("a", "b", "c"), Array(1, 2, 3))
        b = SF_Array.ConvertToDictionary(a)
        MsgBox b.Item("c") ' 3

## ConvertToRange

Create a valid cells range content from a scalar, a 1D array, a 2D array or a data array (a data array is a zero-based array of zero-based subarrays). The lower bounds of arrays are preserved in the output.

Els elements individuals sempre es redueixen a cadenes o enters dobles, incloent-hi booleans o dates.

The returned scalar or 2D array is a valid argument of the session.ExecuteCalcFunction() method. This is particularly useful in the context of [complex] array functions.

### Sintaxi:

svc.ConvertToRange(data: any[0..*, 0..*], direction: str = 'V' | 'H'): any[0..*, 0..*]

### Paràmetres:

data: The input scalar, 1D array,2D array or data array.

direction: The alignment of the range when it is a vector, either "V"[ertical, default] or "H"[orizontal].

### Exemple:

        Dim session As Variant  :  session = CreateScriptService"Session")
        Dim matrix As Variant, result As Variant
        matrix = Array(-1, 2, 3)
        matrix = SF_Array.AppendRow(matrix, Array(4, -5, 6))
        matrix = SF_Array.AppendRow(matrix, Array(7, 8, -9))
        result = session.ExecuteCalcFunction("ABS", SF_Array.ConvertToRange(matrix))
        MsgBox result(2)(2) ' 9 - result is a data array

## Copy

Creates a copy of a 1D or 2D array.

### Sintaxi:

svc.Copy(array_nd: any[0..*]): any[0..*]

svc.Copy(array_nd: any[0..*, 0..*]): any[0..*, 0..*]

### Paràmetres:

array_nd: The 1D or 2D array to be copied.

### Exemple:

A simple assignment of an Array object will copy its reference instead of creating a copy of the object's contents. See the example below:

        Dim a as Variant, b as Variant
        a = Array(1, 2, 3)
        ' The assignment below is made by reference
        b = a
        ' Hence changing values in "b" will also change "a"
        b(0) = 10
        MsgBox a(0) ' 10

By using the Copy method, a copy of the whole Array object is made. In the example below, a and b are different objects and changing values in b will not affect values in a.

        Dim a as Variant, b as Variant
        a = Array(1, 2, 3)
        ' Creates a copy of "a" using the "Copy" method
        b = SF_Array.Copy(a)
        b(0) = 10
        MsgBox a(0) ' 1

## CountDims

Count the number of dimensions of an array. The result can be greater than two.
If the argument is not an array, returns -1
If the array is not initialized, returns 0.

### Sintaxi:

svc.CountDims(array_nd: any): int

### Paràmetres:

array_nd: The array to examine.

### Exemple:

        Dim a(1 To 10, -3 To 12, 5)
        MsgBox SF_Array.CountDims(a) ' 3

## Difference

Construir un conjunt, com una matriu zero, aplicant l’operador diferència a dues matrius d’entrada. Els elements resultants provenen de la primera matriu i no de la segona.
La matriu resultant s'ordena de forma ascendent.
Les dues matrius d’entrada s’han d’omplir de manera homogènia, els seus elements han de ser escalars del mateix tipus. Els elements buits i nuls estan prohibits.
La comparació entre texts pot distingir entre majúscules o minúscules.

### Sintaxi:

svc.Difference(array1_1d: any[0..*], array2_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Paràmetres:

array1_1d: A 1-dimensional reference array, whose items are examined for removal.

array2_1d: A 1-dimensional array, whose items are subtracted from the first input array.

casesensitive: This argument is only applicable if the arrays are populated with strings (Default = False).

### Exemple:

        Dim a As Variant
        a = SF_Array.Difference(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
            ' ("A", "B")

## ExportToTextFile

Escriviu tots els elements de la matriu de manera seqüencial en un fitxer de text. Si el fitxer ja existeix, se sobreescriurà sense previ avís.

### Sintaxi:

svc.ExportToTextFile(array_1d: any[0..*], filename: str, [encoding: str]): bool

### Paràmetres:

array_1d: The array to export. It must contain only strings.

filename: The name of the text file where the data will be written to. The name must be expressed according to the current FileNaming property of the SF_FileSystem service.

encoding: The character set that should be used. Use one of the names listed in IANA character sets. Note that LibreOffice may not implement all existing character sets (Default is "UTF-8").

### Exemple:

        SF_Array.ExportToTextFile(Array("A","B","C","D"), "C:\Temp\A short file.txt")

## ExtractColumn

Extreu d'una matriu de dues dimensions una columna específica com a nova matriu. Els límits
InferiorLBound i superior UBound són idèntics als de la primera dimensió de la matriu d'entrada.

### Sintaxi:

svc.ExtractColumn(array_2d: any[0..*, 0..*], columnindex: int): any[0..*, 0..*]

### Paràmetres:

array_2d: The array from which to extract.

columnindex: The column number to extract - must be in the interval [LBound, UBound].

### Exemple:

        'Crea una matriu 3x3: |1, 2, 3|
        '                      |4, 5, 6|
        '                      |7, 8, 9|
        Dim mat as Variant, col as Variant
        mat = SF_Array.AppendRow(Array(), Array(1, 2, 3))
        mat = SF_Array.AppendRow(mat, Array(4, 5, 6))
        mat = SF_Array.AppendRow(mat, Array(7, 8, 9))
        'Extreu la tercera columna: |3, 6, 9|
        col = SF_Array.ExtractColumn(mat, 2)

## ExtractRow

Extract from a two dimension array a specific row as a new array.
Its lower LBound and upper UBound boundaries are identical to that of the second dimension of the input array.

### Sintaxi:

svc.ExtractRow(array_2d: any[0..*, 0..*], rowindex: int): any[0..*, 0..*]

### Paràmetres:

array_2d: The array from which to extract.

rowindex: The row number to extract - must be in the interval [LBound, UBound].

### Exemple:

        'Crea una matriu 3x3: |1, 2, 3|
        '                      |4, 5, 6|
        '                      |7, 8, 9|
        Dim mat as Variant, row as Variant
        mat = SF_Array.AppendRow(Array(), Array(1, 2, 3))
        mat = SF_Array.AppendRow(mat, Array(4, 5, 6))
        mat = SF_Array.AppendRow(mat, Array(7, 8, 9))
        'Extreu la primera fila: |1, 2, 3|
        row = SF_Array.ExtractRow(mat, 0)

## Flatten

Apila tots els elements individuals d’una matriu i tots els elements de les seves submatrius en una nova matriu sense submatrius. Les submatrius buides s'ignoren i les submatrius amb un nombre de dimensions superior a un no s'aplanen.

### Sintaxi:

svc.Flatten(array_1d: any[0..*]): any[0..*]

### Paràmetres:

array_1d: The pre-existing array, may be empty.

### Exemple:

        Dim a As Variant
        a = SF_Array.Flatten(Array(Array(1, 2, 3), 4, 5))
            ' (1, 2, 3, 4, 5)

You can use the Flatten method along with other methods such as Append or Prepend to concatenate a set of 1D arrays into a single 1D array.

### Exemple:

Next is an example of how the methods Flatten and Append can be combined to concatenate three arrays.

        'Creates three arrays for this example
        Dim a as Variant, b as Variant, c as Variant
        a = Array(1, 2, 3)
        b = Array(4, 5)
        c = Array(6, 7, 8, 9)
        'Concatenates the three arrays into a single 1D array
        Dim arr as Variant
        arr = SF_Array.Flatten(SF_Array.Append(a, b, c))
        '(1, 2, 3, 4, 5, 6, 7, 8, 9)

## ImportFromCSVFile

Import the data contained in a comma-separated values (CSV) file. The comma may be replaced by any character.

El format CSV aplicable es descriu a la pàgina Format comú i tipus MIME de l'IETF per a fitxers CSV (en anglès).

Each line in the file contains a full record (line splitting is not allowed).
However sequences like \n, \t, ... are left unchanged. Use SF_String.Unescape() method to manage them.

The method returns a two dimension array whose rows correspond to a single record read in the file and whose columns correspond to a field of the record. No check is made about the coherence of the field types across columns. A best guess will be made to identify numeric and date types.

If a line contains less or more fields than the first line in the file, an exception will be raised. Empty lines however are simply ignored. If the size of the file exceeds the number of items limit (see inside the code), a warning is raised and the array is truncated.

### Sintaxi:

svc.ImportFromCSVFile(filename: str, delimiter: str = ',', dateformat: str = ''): any[0..*]

### Paràmetres:

filename: The name of the text file containing the data. The name must be expressed according to the current FileNaming property of the SF_FileSystem service.

delimiter: A single character, usually, a comma, a semicolon or a TAB character (Default = ",").

dateformat: A special mechanism handles dates when dateformat is either "YYYY-MM-DD", "DD-MM-YYYY" or "MM-DD-YYYY". The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats will be ignored. Dates defaulting to an empty string "" are considered as normal text.

### Exemple:

Consider the CSV file "myFile.csv" with the following contents:

Name,DateOfBirth,Address,City

Anna,2002/03/31,"Rue de l'église, 21",Toulouse

Fred,1998/05/04,"Rue Albert Einstein, 113A",Carcassonne

The examples below in Basic and Python read the contents of the CSV file into an Array object.

##### En Basic

        Dim arr As Variant
        arr = SF_Array.ImportFromCSVFile("C:\Temp\myFile.csv", DateFormat := "YYYY/MM/DD")
        MsgBox arr(0, 3) ' Ciutat
        MsgBox arr(1, 2) ' Rue de l'église, 21
        MsgBox arr(1, 3) ' Toulouse

##### En Python

        from scriptforge import CreateScriptService
        svc = CreateScriptService("Array")
        bas = CreateScriptService("Basic")
        arr = svc.ImportFromCSVFile(r"C:\Temp\myFile.csv", dateformat = "YYYY/MM/DD")
        bas.MsgBox(arr[0][3]) # Ciutat
        bas.MsgBox(arr[1][2]) # Rue de l'église, 21
        bas.MsgBox(arr[1][3]) # Toulouse

## IndexOf

Look in a one dimension array for a number, a string or a date. Text comparison can be case-sensitive or not.
If the array is sorted it must be filled homogeneously, which means that all items must be scalars of the same type (Empty and Null items are forbidden).
The result of the method is unpredictable when the array is announced as sorted and actually is not.
A binary search is performed on sorted arrays. Otherwise, arrays are simply scanned from top to bottom and Empty and Null items are ignored.
The method returns LBound(input array) - 1 if the search was not successful.

### Sintaxi:

svc.IndexOf(array_1d: any[0..*], tofind: any, casesensitive: bool = False, sortorder: str = ''): int

### Paràmetres:

array_1d: The array to scan.

tofind: A number, a date or a string to find.

casesensitive: Only for string comparisons (Default = False).

sortorder: It can be either "ASC", "DESC" or "" (not sorted). The default value is "".

### Exemple:

        MsgBox SF_Array.IndexOf(Array("A","B","c","D"), "C", SortOrder := "ASC") ' 2
        MsgBox SF_Array.IndexOf(Array("A","B","c","D"), "C", CaseSensitive := True) ' -1

## Insert

Insert before a given index of the input array the items listed as arguments.
Arguments are inserted blindly. Each of them might be either a scalar of any type or a subarray.

### Sintaxi:

svc.Insert(array_1d: any[0..*], before: int, arg0: any, [arg1: any] ...): any[0..*]

### Paràmetres:

array_1d: The pre-existing array, may be empty.

before: The index before which to insert; must be in the interval [LBound, UBound + 1].

arg0, arg1, ...: Items that will be inserted into array_1d.

### Exemple:

        Dim a As Variant
        a = SF_Array.Insert(Array(1, 2, 3), 2, "a", "b")
            ' (1, 2, "a", "b", 3)

## InsertSorted

Inserts into a sorted array a new item on its place.
The array must be filled homogeneously, meaning that all items must be scalars of the same type.
Empty and Null items are forbidden.

### Sintaxi:

svc.InsertSorted(array_1d: any[0..*], item: any, sortorder: str = 'ASC', casesensitive: bool = False): any[0..*]

### Paràmetres:

array_1d: The array into which the value will be inserted.

item: The scalar value to insert, of the same type as the existing array items.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemple:

        Dim a As Variant
        a = SF_Array.InsertSorted(Array("A", "C", "a", "b"), "B", CaseSensitive := True)
            ' ("A", "B", "C", "a", "b")

## Intersection

Build a set, as a zero-based array, by applying the intersection set operator on the two input arrays. Resulting items are contained in both arrays.
The resulting array is sorted in ascending order.
Both input arrays must be filled homogeneously, in other words all items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.

### Sintaxi:

svc.Intersection(array1_1d: any[0..*], array2_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Paràmetres:

array1_1d: The first input array.

array2_1d: The second input array.

casesensitive: Applies to arrays populated with text items (Default = False).

### Exemple:

        Dim a As Variant
        a = SF_Array.Intersection(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
            ' ("C", "b")

## Join2D

Join a two-dimensional array with two delimiters, one for the columns, one for the rows.

### Sintaxi:

svc.Join2D(array_2d: any [0..*, 0..*], [columndelimiter: str], [rowdelimiter: str], [quote: str]): str

### Paràmetres:

array_2d: Each item must be either text, a number, a date or a boolean.
Dates are transformed into the YYYY-MM-DD hh:mm:ss format.
Invalid items are replaced by a zero-length string.

columndelimiter: Delimits each column (default = Tab/Chr(9)).

rowdelimiter: Delimits each row (default = LineFeed/Chr(10))

quote: If True, protect strings with double quotes. The default is False.

### Exemple:

        ' arr = | 1, 2, "A", [2020-02-29], 51, 2, "A", [2020-02-29], 5           |
        '       | 6, 7, "this is a string", 9, 106, 7, "this is a string", 9, 10 |
        Dim arr as Variant : arr = Array()
        arr = SF_Array.AppendRow(arr, Array(1, 2, "A", [2020-02-29], 51, 2, "A", [2020-02-29], 5))
        arr = SF_Array.AppendRow(arr, Array(6, 7, "this is a string", 9, 106, 7, "this is a string", 9, 10))
        Dim arrText as String
        arrText = SF_Array.Join2D(arr, ",", "/", False)
        ' 1,2,A,,51,2,A,,5/6,7,this is a string,9,106,7,this is a string,9,10

## Prepend

Prepend at the beginning of the input array the items listed as arguments.

### Sintaxi:

svc.Prepend(array_1d: any[0..*], arg0: any, [arg1: any] ...): any[0..*]

### Paràmetres:

array_1d: The pre-existing array, may be empty.

arg0, arg1, ...: A list of items to prepend to array_1d.

### Exemple:

        Dim a As Variant
        a = SF_Array.Prepend(Array(1, 2, 3), 4, 5)
            ' (4, 5, 1, 2, 3)

## PrependColumn

Prepend to the left side of a two dimension array a new column. The resulting array has the same lower boundaries as the initial two dimension array.

### Sintaxi:

svc.PrependColumn(array_2d: any[0..*, 0..*], column: any[0..*]): any[0..*, 0..*]

### Paràmetres:

array_2d: The pre-existing array, may be empty. If that array has 1 dimension, it is considered as the last column of the resulting 2 dimension array.

column: A 1-dimensional array with as many items as there are rows in array_2d.

### Exemple:

        Dim a As Variant, b As variant
        a = SF_Array.PrependColumn(Array(1, 2, 3), Array(4, 5, 6))
            ' ((4, 1), (5, 2), (6, 3))
        b = SF_Array.PrependColumn(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(0, i) ≡ i

## PrependRow

Prepend a new row at the beginning of a 2-dimensional array. The resulting array has the same lower boundaries as the initial 2-dimensional array.

### Sintaxi:

svc.PrependRow(array_2d: any[0..*, 0..*], row: any[0..*]): any[0..*, 0..*]

### Paràmetres:

array_2d: The pre-existing array, may be empty. If that array has 1 dimension, it is considered as the last row of the resulting 2-dimensional array.

row: A 1-dimensional array containing as many items as there are columns in array_2d.

### Exemple:

        Dim a As Variant, b As variant
        a = SF_Array.PrependRow(Array(1, 2, 3), Array(4, 5, 6))
            ' ((4, 5, 6), (1, 2, 3))
        b = SF_Array.PrependRow(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(i, 0) ≡ i

## RangeInit

Initialize a new zero-based array with numeric values.

### Sintaxi:

svc.RangeInit(from: num, upto: num, [bystep: num]): num[0..*]

### Paràmetres:

from: Value of the first item.

upto: The last item should not exceed UpTo.

bystep: The difference between two successive items (Default = 1).

### Exemple:

        Dim a As Variant
        a = SF_Array.RangeInit(10, 1, -1)
            ' (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

## Reverse

Return the reversed one dimension input array.

### Sintaxi:

svc.Reverse(array_1d: any[0..*]): any[0..*]

### Paràmetres:

array_1d: The array to reverse.

### Exemple:

        Dim a As Variant
        a = SF_Array.Reverse(Array("a", 2, 3, 4))
            ' (4, 3, 2, "a")

## Shuffle

Retorna una permutació aleatòria d'una matriu unidimensional.

### Sintaxi:

svc.Shuffle(array_1d: any[0..*]): any[0..*]

### Paràmetres:

array_1d: The array to shuffle.

### Exemple:

        Dim a As Variant
        a = SF_Array.Shuffle(Array(1, 2, 3, 4))
            ' La matriu «a» ara està en ordre aleatori; p. ex., (2, 3, 1, 4)

## Slice

Retorna un subconjunt d'una matriu unidimensional.

### Sintaxi:

svc.Slice(array_1d: any[0..*], from: int, [upto: int]): any[0..*]

### Paràmetres:

array_1d: The array to slice.

from: The lower index in array_1d of the subarray to extract (from included)

upto: The upper index in array_1d of the subarray to extract (upto included). The default value is the upper bound of array_1d. If upto < from then the returned array is empty.

### Exemple:

        Dim a As Variant
        a = SF_Array.Slice(Array(1, 2, 3, 4, 5), 1, 3) ' (2, 3, 4)

## Sort

Sort a one dimension array in ascending or descending order. Text comparisons can be case-sensitive or not.
The array must be filled homogeneously, which means that items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.

### Sintaxi:

svc.Sort(array_1d: any[0..*], sortorder: str, casesensitive: bool = False): any[0..*]

### Paràmetres:

array_1d: The array to sort.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemple:

        Dim a As Variant
        a = SF_Array.Sort(Array("a", "A", "b", "B", "C"), CaseSensitive := True)
            ' ("A", "B", "C", "a", "b")

## SortColumns

Return a permutation of the columns of a two dimension array, sorted on the values of a given row.
The row must be filled homogeneously, which means that all items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.

### Sintaxi:

svc.SortColumns(array_2d: any[0..*, 0..*], rowindex: int, sortorder: str, casesensitive: bool = False): any[0..*, 0..*]

### Paràmetres:

array_2d: The 2-dimensional array to sort.

rowindex: The index of the row that will be used as reference to sort the columns.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemple:

        ' arr = | 5, 7, 3 |
        '       | 1, 9, 5 |
        '       | 6, 1, 8 |
        Dim arr as Variant : arr = Array(5, 7, 3)
        arr = SF_Array.AppendRow(arr, Array(1, 9, 5))
        arr = SF_Array.AppendRow(arr, Array(6, 1, 8))
        arr = SF_Array.SortColumns(arr, 2, "ASC")
        ' arr = | 7, 5, 3 |
        '       | 9, 1, 5 |
        '       | 1, 6, 8 |

## SortRows

Return a permutation of the rows of a two dimension array, sorted on the values of a given column.
The column must be filled homogeneously, therefore all items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.

### Sintaxi:

svc.SortRows(array_2d: any[0..*, 0..*], columnindex: int, sortorder: str, casesensitive: bool = False): any[0..*, 0..*]

### Paràmetres:

array_2d: The array to sort.

columnindex: The index of the column that will be used as reference to sort the rows.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemple:

        ' arr = | 5, 7, 3 |
        '       | 1, 9, 5 |
        '       | 6, 1, 8 |
        Dim arr as Variant : arr = Array(5, 7, 3)
        arr = SF_Array.AppendRow(arr, Array(1, 9, 5))
        arr = SF_Array.AppendRow(arr, Array(6, 1, 8))
        arr = SF_Array.SortRows(arr, 0, "ASC")
        ' arr = | 1, 9, 5 |
        '       | 5, 7, 3 |
        '       | 6, 1, 8 |

## Transpose

Swaps rows and columns in a two-dimensional array.

### Sintaxi:

svc.Transpose(array_2d: any[0..*, 0..*]): any[0..*, 0..*]

### Paràmetres:

array_2d: The 2-dimensional array to transpose.

### Exemple:

        ' arr1 = | 1, 2 |
        '        | 3, 4 |
        '        | 5, 6 |
        arr1 = Array(1, 2)
        arr1 = SF_Array.AppendRow(arr1, Array(3, 4))
        arr1 = SF_Array.AppendRow(arr1, Array(5, 6))
        arr2 = SF_Array.Transpose(arr1)
        ' arr2 = | 1, 3, 5 |
        '        | 2, 4, 6 |
        MsgBox arr2(0, 2) ' 5

## TrimArray

Remove from a one dimension array all Null, Empty and zero-length entries.
String items are trimmed with LibreOffice Basic Trim() function.

### Sintaxi:

svc.TrimArray(array_1d: any[0..*]): any[0..*]

### Paràmetres:

array_1d: The array to trim.

### Exemple:

        Dim a As Variant
        a = SF_Array.TrimArray(Array("A", "B", Null, " D "))
            ' ("A", "B", "D")

## Union

Builds a set, as a zero-based array, by applying the union operator on the two input arrays. Resulting items originate from any of both arrays.
The resulting array is sorted in ascending order.
Both input arrays must be filled homogeneously, their items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.

### Sintaxi:

svc.Union(array1_1d: any[0..*], array2_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Paràmetres:

array1_1d: The first input array.

array2_1d: The second input array.

casesensitive: Applicable only if the arrays are populated with strings (Default = False).

### Exemple:

        Dim a As Variant
        a = SF_Array.Union(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
            ' ("A", "B", "C", "Z", "b")

## Unique

Build a set of unique values derived from the input array.
The input array must be filled homogeneously, its items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.

### Sintaxi:

svc.Unique(array_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Paràmetres:

array_1d: The input array.

casesensitive: Applicable only if the array is populated with strings (Default = False).

### Exemple:

        Dim a As Variant
        a = SF_Array.Unique(Array("A", "C", "A", "b", "B"), CaseSensitive := True)
            '  ("A", "B", "C", "b")

Totes les rutines o identificadors bàsics de ScriptForge que tenen el prefix de guió baix "_" estan reservats per a ús intern. No estan pensats per utilitzar-los en macros de Basic o scripts de Python.

Temes relacionats

Funcions de matriu

Using Calc Functions in Macros

ScriptForge.Dictionary service

Ens cal la vostra ajuda!