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?
Solved! Go to Solution.
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))
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))
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...
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.
Just wanted to say thank you for this brief code snippet, Johannes! It more clearly explains filtering Arrays than ESRI's own article.