All Articles

Indexing in PowerApps

Sometimes we may need to access a particular index from a collection in PowerApps. For example, getting the n-th largest value from a collection. Unfortunately, PowerApps doesn’t provide a function for such operation.

Luckily, we can use one work-around using the functions Last and FirstN.

FirstN returns the collection with the first N records. Then we will use the Last function on the resulting collection to get the N-th value from the original collection. Thus, our syntax is:

Last(FirstN(collection_name, N)).property_name

Example

Let’s say we have the following collection of the most populated countries (source: WikiPedia):

Collect(
  colTopPopulationCountries,
  {
    Name: "China",
    Population: "1411 M"
  },
  {
    Name: "India",
    Population: "1382 M"
  },
  {
    Name: "United States",
    Population: "332 M"
  },
  {
    Name: "Indonesia",
    Population: "271 M"
  },
  {
    Name: "Pakistan",
    Population: "225 M"
  }
)

Now, if we want to get the value of 3rd most populated country, we can use:

Last(FirstN(colTopPopulationCountries, 3)).Name

This will give us the value: United States.

I often use this function with Split. Let’s say, we have a string “Value1-Value2-Value3”. We need to extract the values separated by dash (-).

So, first we can split the string using the Split function. The function places the separated string into a collection.

Set(dashSeparatedString, "Value1-Value2-Value3");
Collect(separatedStrings, Split(dashSeparatedString, "-"))

Then, we can use our indexing technique:

Set(val1, Last(FirstN(separatedStrings, 1)).Result);
Set(val2, Last(FirstN(separatedStrings, 2)).Result);
Set(val3, Last(FirstN(separatedStrings, 3)).Result);

Now, the stored values for val1, val2, and val3 will be Value1, Value2, and Value3 respectively.

In this way, we can use this indexing operator to extract specific values from a collection.