CODE MODE: Randomize Array Items with JavaScript Code

  • 31 May 2023
  • 0 replies
  • 41 views

Userlevel 7
Badge +14

CODE MODE: Randomize Array Items with JavaScript Code

 

Contribution by Troy Tessalone

Certified Zapier Expert at Automation Ace

 

ABOUT

If you are looking to randomize an array’s items, then try using a Code step.

 

You can ask ChatGPT by OpenAI for the code to do the randomization.
(Code may need to be tweaked to work in the Zap Code step)

 

Example: JavaScript to Randomize Array Items in Zapier

 

CONFIG

 

CODE

// Extract the 'Set' property from the inputData object
let Set = inputData.Set;

// Check if 'Set' exists
if (Set) {
// If 'Set' exists, split it into an array using commas as the delimiter
Set = Set.split(",");
}

// Define a function to randomize the elements in an array
let randomizeArray = (array) => {
// Iterate over the array starting from the last element
for (let i = array.length - 1; i > 0; i--) {
// Generate a random index from 0 to i (inclusive)
const j = Math.floor(Math.random() * (i + 1));
// Swap the current element with the randomly selected element
[array[i], array[j]] = [array[j], array[i]];
}
// Return the randomized array
return array;
};

// Randomize the 'Set' array using the randomizeArray function
let SetX = randomizeArray([...Set]);

// Assign an array with the original 'Set' and the randomized 'SetX' to the output variable
output = [{ Set, SetX }];

 

RESULTS

 


This post has been closed for comments. Please create a new post if you need help or have a question about this topic.