Select a random item from a data variable containing the array response of an API

Hey guys! Excited to be learning the ropes here. I’m building a web app and I am a little unsure of the best way to achieve the following:

The user clicks ‘Complete’ on a challenge which is returned from an API into a data variable ActiveUserChallenges

The click triggers logic to sent a put request to my API, setting that challenge’s ‘active’ value to 0

Now, I also need to generate a new challenge for the user. I call my API and return a list of possible challenges into another variable, UserChallengesByInterest

However, I can’t work out how I can now select one item from the array UserChallengesByInterest at random (something like a formula to just pick one item) and then return the id so I can trigger another put on my API to set the new challenge’s active value to 1.

Thanks for any advice, and sorry if the answer is staring me in the face.

Hi! I think this should work by using PICK_ITEM(), RANDOM_INTEGER_BETWEEN() and COUNT() together. It would look something like this:

PICK_ITEM(data.UserChallengesByInterest, RANDOM_INTEGER_BETWEEN(0, COUNT(data.UserChallengesByInterest) - 1))

(You gotta subtract 1 from the count so that the integer cannot be higher that the index of the last item in the array.)

And if you’ve used this to set data variable activeChallenge etc, you can check the id later by using LOOKUP(). Something like this:

LOOKUP(data.activeChallenge, "id")

Thank you for this! I will give it a try and let you know how it goes.