Another approach to the problem in your particular example is removing empty elements at the end of the array.
compact
is perhaps the most straightforward, but requires you to rely on using ""
as a sentinel value for Emptiness
.
From the documentation:
compact
takes a list of strings and returns a new list with any empty string elements removed.
> compact(["a", "", "b", "c"])
[
"a",
"b",
"c",
]
I would prefer this over the other answers because it's more idiomatic. I suppose it only works for strings though.
array = compact(["a","b","c", var.age == 12 && var.gender == 'male' ? "d" : ""])`
["a","b","c"] if age != 12 and gender != male
["a","b","c", "d"] if age == 12 and gender == male
Of course the ""
element could be anywhere in your list and compact
would handle this optionality
issue.
I would also be interested in which has the best O()
performance. I don't know how compact
is implemented underneath the hood, but in general you would either copy elements into a new array or you would be shifting elements into gaps left by removed elements.
I don't expect any other solution to be much better than this. Perhaps concat
.
Given that, it probably requires O(n)
comparisons + appends, and then takes O(n)
space because a new list is created.