ArcGIS Online - How to use correct syntax for Filter on Array?

809
4
Jump to solution
12-12-2022 04:55 AM
VincentLaunstorfer
Occasional Contributor III

Hi,

In a PopUp, I am using a simple Arcade expression on which I'd like to count occurrences of a specific value stored in an array:

Count(Filter(myArray, "21"));

For example, I would expect this expression to return the total number of occurrences of value "21". But it returns a syntax error. Why?

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
JohannesLindner
MVP Frequent Contributor

Because you need a function to filter an array: Array functions | ArcGIS Arcade | ArcGIS Developers

 

var arr = [20, 20, 21, 21, 21, 22]
function is_21(x) { return x == 21 }
return Count(Filter(arr, is_21))

JohannesLindner_0-1670851395481.png

 

 

 


Have a great day!
Johannes

View solution in original post

4 Replies
JohannesLindner
MVP Frequent Contributor

Because you need a function to filter an array: Array functions | ArcGIS Arcade | ArcGIS Developers

 

var arr = [20, 20, 21, 21, 21, 22]
function is_21(x) { return x == 21 }
return Count(Filter(arr, is_21))

JohannesLindner_0-1670851395481.png

 

 

 


Have a great day!
Johannes
VincentLaunstorfer
Occasional Contributor III

Thanks. Appreciated.

I did went through the Arcade Developers documentation and found the syntax confusing or cumbersome. When you call the function, you do not send any variable but in the function declaration there is an (x) variable... This x variable is like a 'dummy' variable but if not in the syntax, it produces an error...

0 Kudos
JohannesLindner
MVP Frequent Contributor

You actually never call the function, you pass it to Filter() as an argument.

Passing functions around is something that is not done very often, so it can seem unintuitive, even for people somewhat familiar with programming. Basically, the argument of the function is a placeholder for the elements of the array to which the function is applied.

This is mostly done for code brevity. The expression above could also be written this way:

var arr = [20, 20, 21, 21, 21, 22]
var filter_arr = []
for(var i in arr) {
    if(arr[i] == 21) {
        Push(filter_arr, arr[i])
    }
}
return Count(filter_arr)

 

This is cumbersome to write and read, especially if you have to do it multiple times. To make the code more manageable, we use a predefined function (Filter) that takes care of the for loop.

So, while it may seem confusing, it's actually simply a for loop that returns each element of the array for which the functions returns true.


Have a great day!
Johannes
0 Kudos
Z-man
by
New Contributor II

Just wanted to say thank you for this brief code snippet, Johannes! It more clearly explains filtering Arrays than ESRI's own article.

0 Kudos