Releases And Snippets

How to loop through an array and concatenate text to each item

Hey there! In this blog post, we'll guide you through the process of looping through an array of text and concatenating a piece of text to each item. This can be useful in various scenarios, such as creating more descriptive labels or adding context to data. Let's dive right in!

Step 1: Define Your Array of Text

To begin, you'll need to have an array of text that you want to modify. In our example, we have an array called arrayOfText with the following items:

arrayOfText = ["blue", "orange", "yellow", "red"]

Step 2: Loop Through the Array

Next, we'll use a forEach loop to iterate over each item in the arrayOfText array. This will allow us to perform an action on each individual item.

arrayOfText.forEach(function(item) {
 // Code to modify each item goes here
})

Within the forEach loop, we have access to the current item being processed, represented by the variable item.

Step 3: Update the Variable

Now that we're inside the loop, we can update the item variable by concatenating the desired text to it. To do this, we'll use the Update Variable action in the "Data Manipulation" category.

  1. Select the "Update Variable" action.
  2. Choose the item variable from the dropdown.
  3. Leave the "Update Type" as "Update itself."

Step 4: Concatenate the Text

In the "Update Variable" action, we'll use the concat function to concatenate the desired text to each item.

  1. Click on the "Value" field.
  2. Search for and select the concat function.
  3. Enter the text you want to concatenate as the first argument (e.g., "color ").
  4. Leave the "Separator" argument as a space (" ").
  5. Choose "Text" as the data type for the third argument.

Your "Update Variable" action should look something like this:

Update Variable: item
Update Type: Update itself
Value: concat("color ", item, Text)

Step 5: Save and Run

After configuring the "Update Variable" action, hit the "Save" button to save your changes. Now, when you run your flow, the loop will iterate through each item in the arrayOfText array, concatenating the text "color " to each item.

For example, if your original arrayOfText was ["blue", "orange", "yellow", "red"], the output after running the flow will be:

["color blue", "color orange", "color yellow", "color red"]

And that's it! You've successfully looped through an array of text and concatenated a piece of text to each item. This technique can be applied to various use cases where you need to modify or transform data in an array.

Sign up for Xano

Join 100,000+ people already building with Xano.

Start today and scale to millions.

Start building for free