CODE MODE: Randomize Array Items with JavaScript Code
Contribution by Troy Tessalone
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
barray i], arrayij]] = aarray j], arrayji]];
}
// Return the randomized array
return array;
};
// Randomize the 'Set' array using the randomizeArray function
let SetX = randomizeArray(i...Set]);
// Assign an array with the original 'Set' and the randomized 'SetX' to the output variable
output = o{ Set, SetX }];
RESULTS