I am trying to use IF statements to help build labels for a layer that shows the number of rooms that are within a certain size category. There are five different categories for each building. Each category has its own datafield to store the appropriate number. I want the labels to only display the size category and amount for results greater than zero. That way the label isn't filled up with 0's and wasting space.
Below is what I have tried to write but it has an error with the first IF. Below that is a screenshot of what the labels currently look like.
What I have tried to write which doesn't work
Current labels
Solved! Go to Solution.
Duncan, I found a solution in another post that I was able to modify and make work. See below and thanks for your help!
var label_array = [$feature.SHORT_NAME]
var counts = {
'0-29': $feature.S,
'30-59': $feature.M,
'60-99': $feature.L,
'100-149': $feature.XL,
'150+': $feature.XXL
}
for (var c in counts){
if(counts[c]>0){
Push(
label_array,
`\t${c}: ${counts[c]}`
)
}
}
return Concatenate(
label_array,
'\n'
)
May be your if statements are failing because the number of rooms is a NUMBER? You are querying if it is a TEXT, e.g. $feature.L <> "0" should be $feature.L != 0
I gave that a try and still have an "Invalid expression. Error on line 2. Reserved keyword used." message.
You need to show your new code, stating the error message without context is not that much use. Also when you share code use the insert code button (via the 3 dots), a screen shot is no use as the first thing people want to do is copy your code and attempt to replicate the issue, you can't do that with a screenshot!
Duncan, I found a solution in another post that I was able to modify and make work. See below and thanks for your help!
var label_array = [$feature.SHORT_NAME]
var counts = {
'0-29': $feature.S,
'30-59': $feature.M,
'60-99': $feature.L,
'100-149': $feature.XL,
'150+': $feature.XXL
}
for (var c in counts){
if(counts[c]>0){
Push(
label_array,
`\t${c}: ${counts[c]}`
)
}
}
return Concatenate(
label_array,
'\n'
)
The only thing that I wish I could figure out with the solution is how to set the order in which the label is written from the array. I had hoped that it would sort based on how the array was built, but it writes it alphabetically so the 30-59 and 60-99 categories always show below the 100-149 and 150+ counts.
Looping through a dictionary is always done alphabetically, not in the order that you create it. One way to get around that is to modify the dictionary keys to ensure they're in alphabetical order, then removing that part of the key.
var label_array = [$feature.SHORT_NAME]
var counts = {
"A 0-29": $feature.S,
"B 30-59": $feature.M,
"C 60-99": $feature.L,
"D 100-149": $feature.XL,
"E 150+": $feature.XXL
};
for (var c in counts) {
if (counts[c] > 0) {
Push(label_array, `\t${Mid(c, 2)}: ${counts[c]}`);
}
}
return Concatenate(label_array, "\n");