Array: Difference between revisions

From Bohemia Interactive Community
Jump to navigation Jump to search
(→‎Create an array: wrong results in example)
(43 intermediate revisions by 20 users not shown)
Line 1: Line 1:
==Description==
{{SideTOC}}
An array is a list of items. Each item may be any of the [[:Category:Types|variable types]]. <br>
An '''Array''' is a list of items of varying [[:Category:Types|variable types]]. Different types can coexist within the same array.
The items in an array are referred to as its '''elements'''.<br>
An Array can either be one-dimensional or multi-dimensional.
Arrays have an order. That is, any element in the array comes either before, or after, any other element in the array.
{{Warning | Since {{arma3}} v1.55.133789 arrays are limited to maximum of '''9,999,999''' (sometimes 10,000,000) elements}}


==Declaring Arrays==
Arrays are declared like this:<br>
_array = [elementOne, elementTwo, ..., lastElement]
Each element is either a literal of some type, or an expression of some type.


For example:<br>
== Working with arrays ==
_array = [1, "Word", (1 + [[damage]] [[player]])]
The first two elements are literals (a [[Number]] and a [[String]]), whilst the third is an expression (a [[Number]]).


==Accessing elements==
=== Array properties ===
Every element in the array has an '''index'''. The index says what position the element is in the array. Indices are how elements are accessed. Indices begin at zero, and continue up to (size of array - 1).


The command for accessing elements is [[select|select]]. For example, suppose an array is <br>
An array variable is a '''reference''' to the array (see [https://en.wikipedia.org/wiki/Reference_(computer_science) Wikipedia reference page]);
_array = [soldier1, soldier2, soldier3]
this means that if the array is edited, all the scripts/functions using a reference to this array will see the edition.
Then, (_array [[select]] 0) is _soldier1, and (_array [[select]] 2) is soldier3.


===Looping to access elements===
[[private]] _myArray = ["a", "b", "c"];
In order to loop (or '''''iterate''''') through every element in an array, for any array, we have to know the array's size. <br>
[[private]] _myNewArray = _myArray;
The command for finding an array's size is [[count]].
_myArray [[set]] [1, "z"];
_myNewArray [[select]] 1; {{codecomment|// will be "z"}}


===Index rounding===
An array set through [[setVariable]] does not need to be assigned again if you modify it by reference:
In OFP script, indices are rounded to the nearest whole number.
[[player]] [[setVariable]] ["myArray", ["a", "b", "c"]];
A bounday case (X.5, where X is any whole number) rounds to the nearest '''even''' whole number
[[private]] _myArray = [[player]] [[getVariable]] "myArray";
_myArray [[set]] [1, "z"];
[[player]] [[getVariable]] "myArray"; {{codecomment|// is ["a", "z", "c"]}}


'''Boundary cases:'''<br>
=== Create an array ===
-0.5 rounds up to 0<br>
-0.5 <= index <= 0.5 rounds to 0<br>
0.5 rounds down to 0<br>
0.5 < index < 1.5 rounds to 1<br>
1.5 rounds up to 2<br>
1.5 <= index <= 2.5 rounds to 2<br>
2.5 rounds down to 2<br>
2.5 < index < 3.5 rounds to 3<br>
3.5 rounds up to 4<br>


Other indices follow this pattern.
{{codecomment|// Example of an empty array}}
[[private]] _myArray = [];
[[count]] _myArray; {{codecomment|// returns 0}}
{{codecomment|// Example of a filled array}}
[[private]] _myFilledArray = ["abc", "def"];
[[count]] _myFilledArray; {{codecomment|// returns 2}}


===When an Array index is out of Range===
An array can hold another array within it, that can hold another array itself, etc:
If a rounded index refers to a position in an array that is invalid:
[[private]] _myArray = <nowiki>[["my", "subArray", 1], ["mySubArray2"], [["my", "sub", "sub", "array"]]];</nowiki>
*If the index is negative, an [[Error Zero Divisor]] error message will be displayed.
[[count]] &nbsp;&nbsp;_myArray; {{codecomment|// returns 3}}
*If the index is positive, the returned value will be of the [[Nothing|null type]].
[[count]] &nbsp;(_myArray [[select]] 0); {{codecomment|// returns 3}}
[[count]] &nbsp;(_myArray [[select]] 1); {{codecomment|// returns 1}}
[[count]] &nbsp;(_myArray [[select]] 2); {{codecomment|// returns 1}}
[[count]] ((_myArray [[select]] 2) [[select]] 0); {{codecomment|// returns 4}}


''Accesses which are out of bounds'':<br>
=== Getting an element ===
_array = []
_element = (_array select 0)


_array = ["element"]
An array uses a zero-based index for its elements:
_element = (_array select 1)


  _array = ["element"]
  [[private]] _myArray = ["first item", "second item", "third item"];
  _element = (_array select -1)
  _myArray [[select]] 0; {{codecomment|// returns "first item"}}
''Accesses which are in bounds'':
  _myArray [[a_hash_b|#]] 2; {{codecomment|// returns "third item" - {{arma3}} only}}
  _array = ["element"]
_element = (_array select 0)


_array = ["element"]
=== Setting an element ===
_element = (_array select 0.1)


  _array = ["element"]
  [[private]] _myArray = ["first item", "second item", "third item"];
  _element = (_array select -0.3)
  _myArray [[select]] 1; {{codecomment|// returns "second item"}}
_myArray [[set]] [1, "hello there"]; {{codecomment|// _myArray is ["first item", "hello there", "third item"]}}


==Changing an array==
{{Important | If the index given to the [[set]] command is out of bounds, the array will [[resize]] to incorporate the index ''as its last value''.
All the "empty spaces" between the last valid element and the new [[set]] element will be filled with [[nil]]}}


There are two types of operations to change an array: operations which change the underlying array, and operations which return a new array, but leave the old array intact.
=== Counting elements ===


===Array references===
[[private]] _myArray = ["first item", "second item", "third item"];
[[count]] _myArray; {{codecomment|// returns 3}}


Array variables behave the same as [[Object]] references, and differently to [[String]], [[Number]] and other variable types. An array variable holds a '''''pointer''''' to an array, or in other words, the location of an array. Any number of different variables can refer to the same array.
=== Changing array size ===


Analogy using [[Object|Objects]]:<br>
The [[resize]] command is made to reduce or expand an array:
_unit1 = player<br>
  [[private]] _myArray = [1, 2, 3, 4, 5];
  _unit2 = player
_myArray [[resize]] 3; {{codecomment|// _myArray is [1, 2, 3]}}
The commands (player [[setDamage]] 0.5), (_unit1 [[setDamage]] 0.5) and (_unit2 [[setDamage]] 0.5) all have the same effect, since they all refer to the same object (the [[player]]).


It is a similar case with arrays:<br>
  [[private]] _myArray = [1, 2, 3];
  _array = [1,2,3]<br>
  _myArray [[resize]] 5; {{codecomment|// _myArray is [1, 2, 3, [[nil]], [[nil]]]}}
  _array1 = _array<br>
_array2 = _array
The commands (_array [[set]] [0, 7]), (_array1 [[set]] [0, 7]) and (_array2 [[set]] [0, 7]) all have the same effect, since they all refer to the same array.


===Setting elements===
{{Important | You do '''not''' need to extend an array before adding elements!}}
Individual elements in an array can be set to different values.<br>
This is done via the [[set]] operator. '''It is important to declare the array before using the [[set]] operator.'''


The previous element at the specified index gets replaced with the new one.
=== Array Copy ===


Example:<br>
  [[private]] _myArray = ["a", "b", "c"];
  _array = [1,2,3]<br>
  [[private]] _myNewArray = _myArray;
  _array [[set]] [2, "Hello"]
_myArray [[set]] [1, "z"];
Now, _array is [1, 2, "Hello"]. The 2nd index (which is the third element in the array, which was 3) gets replaced by "Hello".
_myNewArray [[select]] 1; {{codecomment|// will be "z"}}


If the index given by the [[set]] operator is out of bounds,
[[private]] _myArray = <nowiki>[["a", "b", "c"], ["d", "e", "f"];</nowiki>
* If the index rounded to a negative number, then an [[Error Zero Divisor]] message will be displayed in game.
[[private]] _subArray1 = _myArray [[select]] 0;
* If the index rounded to a positive number, then the array will '''''resize''''' to incorporate the index ''as its last value''. Each element between the last valid element, and the new [[set]] element, will be the [[Nothing|null type]]
_subArray1 [[set]] [1, "z"];
{{codecomment|// _subArray1 is now ["a", "z", "c"]}}
{{codecomment|// _myArray is now <nowiki>[["a", "z", "c"], ["d", "e", "f"]]</nowiki>}}
 
In order to avoid this behaviour, '''copy''' the array with [[+|+ (plus)]]:
 
{{codecomment|// making copy}}
[[private]] _myArray = ["a", "b", "c"];
[[private]] _myNewArray = [[+]]_myArray;
_myArray [[set]] [1, "z"];
_myNewArray [[select]] 1; {{codecomment|// still "b"}}
 
Sub-arrays are also deep-copied {{Inline code|_myNewArray}} will not point at the same sub-array instances.
 
=== Adding (appending) elements ===
 
In {{arma3}} use [[append]] and [[pushBack]] commands:
 
[[private]] _myArray = [1, 2, 3];
_myArray [[pushBack]] 4; {{codecomment|// _myArray is [1, 2, 3, 4]}}
_myArray [[append]] [5, 6]; {{codecomment|// _myArray is [1, 2, 3, 4, 5, 6]}}
 
You could also use [[+| (+)]] operator to add arrays. The difference is that addition returns a copy of array and thus  [[Code Optimisation#Adding elements |a little slower]] than [[append]] and [[pushBack]], which modify target array.
 
[[private]] _myArray = [1, 2, 3];
_myArray = _myArray [[+]] [4]; {{codecomment|// _myArray is [1, 2, 3, 4]}}
_myArray = _myArray [[+]] [5, 6]; {{codecomment|// _myArray is [1, 2, 3, 4, 5, 6]}}
 
=== Removing (deleting) elements ===
 
In {{arma3}} the [[deleteAt]] and [[deleteRange]] commands are available:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
_myArray [[deleteAt]] 0; {{codecomment|// _myArray is [2, 3, 4, 5]}}
 
[[private]] _myArray = [1, 2, 3, 4, 5];
_myArray [[deleteRange]] [1, 2]; {{codecomment|// _myArray is [1, 4, 5]}}
 
You can also use [[-|(-)]] operator to subtract arrays. The subtraction returns array copy, just like addition, and this [[Code Optimisation#Removing elements|not as fast]] as [[deleteAt]] and [[deleteRange]] which modify target arrays.
 
[[private]] _myArray = [1, 2, 3, 4, 5];
_myArray = _myArray [[-]] [1]; {{codecomment|// _myArray is [2, 3, 4, 5]}}
 
In {{arma3}} it became possible to also subtract nested arrays:
 
[[private]] _myArray = <nowiki>[[1, 2, 3], [4, 5, 6], [7, 8, 9]];</nowiki>
_myArray = _myArray [[-]] <nowiki>[[4, 5, 6]];</nowiki> {{codecomment|// _myArray is <nowiki>[[1, 2, 3], [7, 8, 9]]</nowiki>}}
 
The subtraction will remove ''all'' elements of second array from the first array:
 
_myArray = [1, 2, 3, 1, 2, 3] [[-]] [1, 2]; {{codecomment|// _myArray is [3, 3]}}
 
The solution to this issue is the combined use of [[set]] and an item that you know is '''not''' present in the array:
 
[[private]] _myArray = [1, 2, 3, 1, 2, 3];
_myArray [[set]] [2, [[objNull]]]; {{codecomment|// _myArray is [1, 2, [[objNull]], 1, 2, 3]]}}
_myArray = _myArray [[-]] <nowiki>[</nowiki>[[objNull]]]; {{codecomment|// _myArray is [1, 2, 1, 2, 3]]}}
 
Using this technique, it is possible to mimic [[deleteRange]] behaviour this way:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
{ _myArray [[set]] [_x, [[objNull]]] } [[forEach]] [1, 2]; {{codecomment|// _myArray is [1, [[objNull]], [[objNull]], 4, 5]}}
_array = _array [[-]] [objNull]; {{codecomment|// _myArray is [1, 4, 5]}}
 
=== Going through the array ===
 
The simplest way to iterate through an array is the [[forEach]] command:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
{ [[systemChat]] [[str]] [[_x]] } [[forEach]] _myArray;
 
A combination of [[for]], [[count]] and [[select]] can also be used:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
[[for]] "_i" [[from]] 0 [[to]] '''([[count]] _myArray) -1''' [[do]] { {{codecomment|// [[count]] would return 5, but 5 is at array index 4}}
[[systemChat]] [[str]] (_myArray [[select]] _i);
};
 
 
== Advanced usage ==
 
=== apply ===
 
Similar to the [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map "map" function in Javascript],
[[apply]] allows to apply code to every elements in an array and return a copy:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
_myArray = _myArray [[apply]] { [[_x]] [[*]] 2 }; {{codecomment|// _myArray is [2, 4, 6, 8, 10]}}
{{codecomment|// same as}}
_myArray =+ _myArray;
[[for]] "_i" [[from]] 0 [[to]] [[count]] _myArray -1 [[do]] {
[[private]] _element = _myArray [[select]] _i;
_myArray [[set]] [_i, _element [[*]] 2];
};
 
=== select ===
 
A simple way to filter an array (and obtain a new one) is using [[select]]'s alternative syntax:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
[[private]] _filteredArray = _myArray [[select]] { [[_x]] > 3 }; {{codecomment|// _filteredArray is [4, 5]}}
{{codecomment|// same as}}
[[private]] _filteredArray = [];
{ [[if]] ([[_x]] > 3) [[then]] { _filteredArray [[pushBack]] [[_x]] } } [[forEach]] _myArray;
 
=== findIf ===
 
The [[findIf]] command was introduced in {{arma3}} and allows you to go through the whole list and stop '''as soon as the condition is met''', returning the condition-meeting element's array index:
 
[[private]] _myArray = [1, 2, 3, 4, 5];
_myArray [[findIf]] { [[_x]] == 3 } > -1; {{codecomment|// returns [[true]], meaning there is an element that equals 3}}
_myArray [[findIf]] { [[_x]] == 6 } > -1; {{codecomment|// returns [[false]], meaning there is no element that is equal to 6}}
 
You could use [[count]] to achieve the same result, however [[count]] won't stop until it iterated through the whole array, so it might take [[Code Optimisation#findIf|longer]].
 
[[private]] _myArray = [1, 2, 3, 4, 5];
{ [[_x]] == 3 } [[count]] _myArray > 0; {{ codecomment|// returns [[true]], meaning there is an element that equals 3}}
{ [[_x]] == 6 } [[count]] _myArray > 0; {{ codecomment|// returns [[false]], meaning there is no element that is equal to 6}}
 
=== arrayIntersect ===
 
The [[arrayIntersect]] command returns a new array filled with the items found in both provided lists:
 
[[private]] _array1 = [1, 2, 3, 4];
[[private]] _array2 = [3, 4, 5, 6];
[[private]] _result = _array1 [[arrayIntersect]] _array2; {{codecomment|// _result is [3, 4]}}
 
=== Sorting an array ===
 
==== sort ====
 
The [[sort]] command allows for sorting an array of [[String]], [[Number]] or sub-[[Array]]s of string/number. It modifies the original array and '''does not return anything''':
 
[[private]] _myArray = ["zzz", "aaa", "ccc"];
_myArray [[sort]] [[true]]; {{codecomment|// _myArray is ["aaa", "ccc", "zzz"]}}
 
[[private]] _myArray = [666, 57, 1024, 42];
_myArray [[sort]] [[false]]; {{codecomment|// _myArray is [1024, 666, 57, 42]}}
 
[[private]] _myArray = <nowiki>[["zzz", 0], ["aaa", 42], ["ccc", 33]];</nowiki>
_myArray [[sort]] [[true]]; {{codecomment|// _myArray is <nowiki>[["aaa", 42], ["ccc", 33], ["zzz", 0]]</nowiki>}}
 
==== reverse ====
 
The [[reverse]] command simply reverses the array order:
[[private]] _myArray = [99, 33, 17, 24, "a", [3,2,1], 7777];
[[reverse]] _myArray; {{codecomment|// _myArray is [7777, [3,2,1], "a", 24, 17, 33, 99]}}


Example:<br>
==== BIS_fnc_sortBy ====
_array = [1]<br>
_array [[set]] [3, 4]
Now _array is [1, <Null>, <Null>, 4]


==Array copying, addition and substraction==
The function [[BIS_fnc_sortBy]] has been created for more complex sorting. Its algorithm input must return a number:


Each of these commands returns a new array, and leaves the old array or arrays unchanged.
[[private]] _closestHelicopters = <nowiki>[</nowiki>[_heli1, _heli2, _heli3], [], { [[player]] [[distance]] [[_x]] }, "ASCEND"] [[call]] [[BIS_fnc_sortBy]];


===Copying===


This is done by the [[plus a|+]] unary operator. It copies an array, and sets the array variable to point to this new array.
== Common errors ==


Example:<br>
=== Index rounding ===
_array1 = [1,2,3]<br>
In Arma scripts, indices are rounded to the nearest whole number.
_array2 = + _array1
A boundary case (X.5, where X is any whole number) rounds to the nearest '''even''' whole number.
Now _array and _array2 point to 2 different arrays, both of which have the contents [1,2,3].


===Addition===
;Boundary cases:
* -0.5 <= index <= 0.5 rounds to 0
* &nbsp;0.5 <&nbsp; index <&nbsp; 1.5 rounds to 1
* &nbsp;1.5 <= index <= 2.5 rounds to 2
* &nbsp;2.5 <&nbsp; index <&nbsp; 3.5 rounds to 3


This is done by the [[a plus b|+]] binary operator. It takes two arrays, and returns a new array which containes all of the first array, followed by all of the second array.
;In short:
* -0.5 rounds '''up''' to 0
* &nbsp;0.5 rounds '''down''' to 0
* &nbsp;1.5 rounds '''up''' to 2
* &nbsp;2.5 rounds '''down''' to 2
* &nbsp;3.5 rounds '''up''' to 4
etc.


Example:<br>
=== Index out of Range ===
_array1 = [player, 7, "String"]<br>
_array2 = [player, 2]<br>
_array3 = _array1 + _array2
After this _array3 refers to a new array which has the contents [player, 7, "String", player, 2]


Another example, using set:<br>
The following code lists {{arma3}} behaviour on wrong indices:
_array set [count _array, "String"];


===Subtraction===
[[private]] _myArray = ["element0"];
_myArray [[select]] -1; {{codecomment|// throws a [[Error Zero Divisor]] error message}}
_myArray [[select]] &nbsp;0; {{codecomment|// returns "element0"}}
_myArray [[select]] &nbsp;1; {{codecomment|// returns [[nil]]}}
_myArray [[select]] &nbsp;2; {{codecomment|// throws a [[Error Zero Divisor]] error message}}


This is done by the [[a - b|-]] binary operator. It takes 2 arrays, and returns a new array that contains all of the items in the first array that were '''''not''''' in the second array.
==== set ====


Example:<br>
If the index given to the [[set]] command is out of bounds:
_array1 = [1,2,player,2,"String","String",3]<br>
* If the index rounded to a negative number, then an [[Error Zero Divisor]] message will be displayed in game.
_array2 = [2,player,"String"]<br>
* If the index rounded to a positive number, then the array will [[resize]] to incorporate the index ''as its last value''. Each element between the last valid element, and the new [[set]] element, will be the [[Nothing|null type]]
_array3 = _array1 - _array2


The result is that _array3 is a new array which has the contents [1, 3].
=== Bad syntax ===


'''Note:'''<br>
{{codecomment|// Error: Unexpected ","}}
*Subtracting an array from itself will always return an empty array [].
[[private]] _myErroneousArray = ["Weapon1", "Weapon2", "Weapon3",]; {{codecomment|// The last element in an array must exclude the ","}}


*Nested arrays ''cannot'' be substracted - i.e. the following does NOT work:
_a1 = [[1,1],[2,2],[3,3]];
_a2 = <nowiki>[[</nowiki>2,2<nowiki>]]</nowiki>;
_a3 = _a1 - _a2; // will still return [[1,1],[2,2],[3,3]]


[[Category: Data Types]]
[[Category: Data Types]]

Revision as of 04:24, 5 August 2019

Template:SideTOC An Array is a list of items of varying variable types. Different types can coexist within the same array. An Array can either be one-dimensional or multi-dimensional.

Since Arma 3 v1.55.133789 arrays are limited to maximum of 9,999,999 (sometimes 10,000,000) elements


Working with arrays

Array properties

An array variable is a reference to the array (see Wikipedia reference page); this means that if the array is edited, all the scripts/functions using a reference to this array will see the edition.

private _myArray = ["a", "b", "c"];
private _myNewArray = _myArray;
_myArray set [1, "z"];
_myNewArray select 1; // will be "z"

An array set through setVariable does not need to be assigned again if you modify it by reference:

player setVariable ["myArray", ["a", "b", "c"]];
private _myArray = player getVariable "myArray";
_myArray set [1, "z"];
player getVariable "myArray"; // is ["a", "z", "c"]

Create an array

// Example of an empty array
private _myArray = [];
count _myArray;			// returns 0

// Example of a filled array
private _myFilledArray = ["abc", "def"];
count _myFilledArray;	// returns 2

An array can hold another array within it, that can hold another array itself, etc:

private _myArray = [["my", "subArray", 1], ["mySubArray2"], [["my", "sub", "sub", "array"]]];
count   _myArray;						// returns 3
count  (_myArray select 0);				// returns 3
count  (_myArray select 1);				// returns 1
count  (_myArray select 2);				// returns 1
count ((_myArray select 2) select 0);	// returns 4

Getting an element

An array uses a zero-based index for its elements:

private _myArray = ["first item", "second item", "third item"];
_myArray select 0;	// returns "first item"
_myArray # 2;		// returns "third item" - Arma 3 only

Setting an element

private _myArray = ["first item", "second item", "third item"];
_myArray select 1;					// returns "second item"
_myArray set [1, "hello there"];	// _myArray is ["first item", "hello there", "third item"]
If the index given to the set command is out of bounds, the array will resize to incorporate the index as its last value. All the "empty spaces" between the last valid element and the new set element will be filled with nil

Counting elements

private _myArray = ["first item", "second item", "third item"];
count _myArray; // returns 3

Changing array size

The resize command is made to reduce or expand an array:

private _myArray = [1, 2, 3, 4, 5];
_myArray resize 3; // _myArray is [1, 2, 3]
private _myArray = [1, 2, 3];
_myArray resize 5; // _myArray is [1, 2, 3, nil, nil]
You do not need to extend an array before adding elements!

Array Copy

private _myArray = ["a", "b", "c"];
private _myNewArray = _myArray;
_myArray set [1, "z"];
_myNewArray select 1; // will be "z"
private _myArray = [["a", "b", "c"], ["d", "e", "f"];
private _subArray1 = _myArray select 0;
_subArray1 set [1, "z"];
// _subArray1 is now ["a", "z", "c"]
// _myArray is now [["a", "z", "c"], ["d", "e", "f"]]

In order to avoid this behaviour, copy the array with + (plus):

// making copy
private _myArray = ["a", "b", "c"];
private _myNewArray = +_myArray;
_myArray set [1, "z"];
_myNewArray select 1; // still "b"

Sub-arrays are also deep-copied _myNewArray will not point at the same sub-array instances.

Adding (appending) elements

In Arma 3 use append and pushBack commands:

private _myArray = [1, 2, 3];
_myArray pushBack 4;		// _myArray is [1, 2, 3, 4]
_myArray append [5, 6];		// _myArray is [1, 2, 3, 4, 5, 6]

You could also use (+) operator to add arrays. The difference is that addition returns a copy of array and thus a little slower than append and pushBack, which modify target array.

private _myArray = [1, 2, 3];
_myArray = _myArray + [4];		// _myArray is [1, 2, 3, 4]
_myArray = _myArray + [5, 6];	// _myArray is [1, 2, 3, 4, 5, 6]

Removing (deleting) elements

In Arma 3 the deleteAt and deleteRange commands are available:

private _myArray = [1, 2, 3, 4, 5];
_myArray deleteAt 0; // _myArray is [2, 3, 4, 5]
private _myArray = [1, 2, 3, 4, 5];
_myArray deleteRange [1, 2];	// _myArray is [1, 4, 5]

You can also use (-) operator to subtract arrays. The subtraction returns array copy, just like addition, and this not as fast as deleteAt and deleteRange which modify target arrays.

private _myArray = [1, 2, 3, 4, 5];
_myArray = _myArray - [1]; // _myArray is [2, 3, 4, 5]

In Arma 3 it became possible to also subtract nested arrays:

private _myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

_myArray = _myArray - [[4, 5, 6]]; // _myArray is [[1, 2, 3], [7, 8, 9]]

The subtraction will remove all elements of second array from the first array:

_myArray = [1, 2, 3, 1, 2, 3] - [1, 2]; // _myArray is [3, 3]

The solution to this issue is the combined use of set and an item that you know is not present in the array:

private _myArray = [1, 2, 3, 1, 2, 3];
_myArray set [2, objNull];			// _myArray is [1, 2, objNull, 1, 2, 3]]
_myArray = _myArray - [objNull];	// _myArray is [1, 2, 1, 2, 3]]

Using this technique, it is possible to mimic deleteRange behaviour this way:

private _myArray = [1, 2, 3, 4, 5];
{ _myArray set [_x, objNull] } forEach [1, 2];	// _myArray is [1, objNull, objNull, 4, 5]
_array = _array - [objNull];					// _myArray is [1, 4, 5]

Going through the array

The simplest way to iterate through an array is the forEach command:

private _myArray = [1, 2, 3, 4, 5];
{ systemChat str _x } forEach _myArray;

A combination of for, count and select can also be used:

private _myArray = [1, 2, 3, 4, 5];
for "_i" from 0 to (count _myArray) -1 do { // count would return 5, but 5 is at array index 4
	systemChat str (_myArray select _i);
};


Advanced usage

apply

Similar to the "map" function in Javascript, apply allows to apply code to every elements in an array and return a copy:

private _myArray = [1, 2, 3, 4, 5];
_myArray = _myArray apply { _x * 2 }; // _myArray is [2, 4, 6, 8, 10]

// same as
_myArray =+ _myArray;
for "_i" from 0 to count _myArray -1 do {
	private _element = _myArray select _i;
	_myArray set [_i, _element * 2];
};

select

A simple way to filter an array (and obtain a new one) is using select's alternative syntax:

private _myArray = [1, 2, 3, 4, 5];
private _filteredArray = _myArray select { _x > 3 }; // _filteredArray is [4, 5]

// same as
private _filteredArray = [];
{ if (_x > 3) then { _filteredArray pushBack _x } } forEach _myArray;

findIf

The findIf command was introduced in Arma 3 and allows you to go through the whole list and stop as soon as the condition is met, returning the condition-meeting element's array index:

private _myArray = [1, 2, 3, 4, 5];
_myArray findIf { _x == 3 } > -1; // returns true, meaning there is an element that equals 3
_myArray findIf { _x == 6 } > -1; // returns false, meaning there is no element that is equal to 6

You could use count to achieve the same result, however count won't stop until it iterated through the whole array, so it might take longer.

private _myArray = [1, 2, 3, 4, 5];
{ _x == 3 } count _myArray > 0; // returns true, meaning there is an element that equals 3
{ _x == 6 } count _myArray > 0; // returns false, meaning there is no element that is equal to 6

arrayIntersect

The arrayIntersect command returns a new array filled with the items found in both provided lists:

private _array1 = [1, 2, 3, 4];
private _array2 = [3, 4, 5, 6];
private _result = _array1 arrayIntersect _array2; // _result is [3, 4]

Sorting an array

sort

The sort command allows for sorting an array of String, Number or sub-Arrays of string/number. It modifies the original array and does not return anything:

private _myArray = ["zzz", "aaa", "ccc"];
_myArray sort true; // _myArray is ["aaa", "ccc", "zzz"]
private _myArray = [666, 57, 1024, 42];
_myArray sort false; // _myArray is [1024, 666, 57, 42]
private _myArray = [["zzz", 0], ["aaa", 42], ["ccc", 33]];
_myArray sort true; // _myArray is [["aaa", 42], ["ccc", 33], ["zzz", 0]]

reverse

The reverse command simply reverses the array order:

private _myArray = [99, 33, 17, 24, "a", [3,2,1], 7777];
reverse _myArray; // _myArray is [7777, [3,2,1], "a", 24, 17, 33, 99]

BIS_fnc_sortBy

The function BIS_fnc_sortBy has been created for more complex sorting. Its algorithm input must return a number:

private _closestHelicopters = [[_heli1, _heli2, _heli3], [], { player distance _x }, "ASCEND"] call BIS_fnc_sortBy;


Common errors

Index rounding

In Arma scripts, indices are rounded to the nearest whole number. A boundary case (X.5, where X is any whole number) rounds to the nearest even whole number.

Boundary cases
  • -0.5 <= index <= 0.5 rounds to 0
  •  0.5 <  index <  1.5 rounds to 1
  •  1.5 <= index <= 2.5 rounds to 2
  •  2.5 <  index <  3.5 rounds to 3
In short
  • -0.5 rounds up to 0
  •  0.5 rounds down to 0
  •  1.5 rounds up to 2
  •  2.5 rounds down to 2
  •  3.5 rounds up to 4

etc.

Index out of Range

The following code lists Arma 3 behaviour on wrong indices:

private _myArray = ["element0"];
_myArray select -1; // throws a Error Zero Divisor error message
_myArray select  0; // returns "element0"
_myArray select  1; // returns nil
_myArray select  2; // throws a Error Zero Divisor error message

set

If the index given to the set command is out of bounds:

  • If the index rounded to a negative number, then an Error Zero Divisor message will be displayed in game.
  • If the index rounded to a positive number, then the array will resize to incorporate the index as its last value. Each element between the last valid element, and the new set element, will be the null type

Bad syntax

// Error: Unexpected ","
private _myErroneousArray = ["Weapon1", "Weapon2", "Weapon3",]; // The last element in an array must exclude the ","