Skip to main content
pearlf4501
New Participant
Sep 8, 2024 8:53 PM UTC
Question

Most efficient way to replace null values in an array with 0?

Currently using a!forEach and a!isNullOrEmpty to replace all null values in an array of integers with 0, but would love to learn the most efficient way to do so. Is apply() the way to go here? A different function? Many thanks for any and all help!

3 replies

kumara0180
Participating Frequently
Sep 8, 2024 9:12 PM UTC

If you just need to remove the null values from array then I would just to use remove(a!isnull,<array>).

But if you really have to replace then I would suggest not to use apply. 

Brainy
Sep 9, 2024 5:33 AM UTC

The following code snippet might be helpful:

a!localVariables(
  local!data: { 1, null, 0, 10, null },
  local!updatedData: a!update(
    local!data,
    wherecontains(tointeger(null()), local!data),
    0
  ),
  local!updatedData
)

peter.lewis
Employee
Sep 9, 2024 12:30 PM UTC

Luckily the a!defaultValue() function does exactly what you're looking for! You just have to run it using a!forEach() to apply it to a list of values:

a!localVariables(
  local!data: {1, 2, null, 4, null, 6},
  a!forEach(
    items: local!data,
    expression: a!defaultValue(
      value: fv!item,
      default: 0
    )
  )
)

Also you asked about the apply() function - at this point, everything that the apply function does can also be done by a!forEach(), so I recommend using a!forEach() instead if you need to loop over a list of values.