Page MenuHomeFeedback Tracker

New function BIS_fnc_findValueInPairArray
New, NormalPublic

Description

I'd like to propose a new function i'm already using in many of my scripts. This function is inpired from BIS_fnc_findInPairs andd it is very useful:

  • Description: Searches the associative array for the first occurance of specified value and returns its index. Seach is not case-sensitive.
  • Syntax: [array, value, column] call BIS_fnc_findValueInPairArray
  • Parameters: array: Array - array to search through | value: any - value to search for | column (Optional): Number - column to search in, (default 0)

Return Value:

Number - index of first occurence or -1

Details

Severity
Minor
Resolution
Open
Reproducibility
Always
Operating System
Windows 11 x64
Operating System Version
23H2
Category
Scripting
Steps To Reproduce

Here is the code:

        params ["_array", "_value", ["_column", 0]];
	private["_toReturn"];

	_toReturn = -1;
	for [{ _i = 0 }, { _i < count _array }, { _i = _i + 1 }] do {
		if(((_array select _i) select _column) isEqualTo _value) then {
			_toReturn = _i;
                        break;
		};
	};
	_toReturn;

Event Timeline

XTankKiller updated the task description. (Show Details)Jun 3 2024, 11:14 AM
XTankKiller updated the task description. (Show Details)
XTankKiller updated the task description. (Show Details)

Here is another way to code this function, proposed by Sa-Matra and this way is 20-25% faster:

params ["_array", "_value", ["_column", 0]];
private _index = {if(_x param [_column] isEqualTo _value) exitWith {_forEachIndex};} forEach _array;
if(isNil"_index") then {-1} else {_index};

Congrats to him.

params ["_array", "_value", ["_column", 0]];
private _index = {if(_x param [_column] isEqualTo _value) exitWith {_forEachIndex};} forEach _array;
[_index, -1] select (isNil"_index");

This way is even faster.

Leopard20 added a subscriber: Leopard20.EditedJun 3 2024, 4:40 PM

Using findIf is even faster. Another implementation is:

params ["_array", "_value", ["_column", 0]];
private _valueArray = [_value];
private _column =  [_column, 1];
_array findIf {_x select _column isEqualTo _valueArray };

Which should be even faster (although it behaves differently from above, and the array must be an array of arrays, not array of values)