Help updating an array element

Hello,

What is the best way to update an array element in FQL?

For example, incrementing the below array’s value at zero-based index 2 from 3 to 4

Let(
  {
    array: [1, 2, 3, 4, 5],
  },
  # ???
)
 # should result in [1, 2, 4, 4, 5]

I see that I can use Select to get an array value at a specific index, but couldn’t find any equivalent function for setting values at a specific index.

I also considered using a Foreach or Map to iterate the array, but I don’t see any documentation indicating the associated Lambda can access the current iteration’s array index.

Apologies if this has already been asked before or is covered in the docs. I searched, but may have missed something.

Thanks,
Ross

So my brain turned on and realized I could use Reduce for this.

Would still be interested in hearing if there’s a more direct way to update an array element at a given index, but for now this approach is working for me.

Let(
  {
    array: [1, 2, 3, 4, 5],
    incrementIndex: 2
  },
  Reduce(
    Lambda(
      ["acc", "value"],
      If(
        Equals(Count(Var("acc")), Var("incrementIndex")),
        Append(Add(Var("value"), 1), Var("acc")),
        Append(Var("value"), Var("acc"))
      )
    ),
    [],
    Var("array")
  )
)

# [1, 2, 4, 4, 5]

You are on the right track! An array element cannot be updated in place; the whole thing does need to be modified and provided to the Update function.

Check out this previous topic:

Ohh! Very interesting. Not sure how I missed that forum post, but it looks like a cleaner solution than what I came up with. Thank you! :v:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.