Function Repository Resource:

SelectFirstIndex

Source Notebook

Find the index of the first element satisfying a criterion

Contributed by: Taliesin Beynon

ResourceFunction["SelectFirstIndex"][{e1,e2,},crit]

gives the first i for which crit[ei] yields True.

ResourceFunction["SelectFirstIndex"][list,crit,default]

gives default if no element yields True.

ResourceFunction["SelectFirstIndex"][crit]

is the operator form of ResourceFunction["SelectFirstIndex"].

Details and Options

If no default is specified, ResourceFunction["SelectFirstIndex"] returns Missing["NotFound"] if no element matches.
ResourceFunction["SelectFirstIndex"] has attribute HoldRest.

Examples

Basic Examples (3) 

Find the index of the first element satisfying a criterion:

In[1]:=
ResourceFunction["SelectFirstIndex"][{1, 2, 3}, EvenQ]
Out[1]=

When no element can be found, a Missing object is returned:

In[2]:=
ResourceFunction["SelectFirstIndex"][{1, 2, 3}, # > 10 &]
Out[2]=

Specify the default value for the missing element:

In[3]:=
ResourceFunction["SelectFirstIndex"][{1, 2, 3}, # > 10 &, "NotFound"]
Out[3]=

Use the operator form of SelectFirstIndex:

In[4]:=
ResourceFunction["SelectFirstIndex"][# > 2 &][{1, 2, 3}]
Out[4]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 04 February 2019

License Information