Mar 30, 2020 07:13 AM
Does anyone know a script that I can use as follows: 1) take a field that has a string of 10-12 Comma Separated Values (CSV) and 2) randomize the order of those 10-12 values?
I’m not a technical person, so I’m sorry if this is a rudimentary question…
Mar 30, 2020 09:01 AM
Part 1
let myArray = csvString.split(",");
Part 2
let myShuffledArray = shuffle(myArray);
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
Mar 30, 2020 04:14 PM
Thanks Bill…I’m really not technical. Is it possible to walk me through a little bit re how to do this? This is my first time using this block…or attempting to “code” for that matter. Think of me like a 7-year old child, though I’m sure that’s an insult to many 7-year olds :frowning:
Mar 30, 2020 05:45 PM
They can handle it.
Here’s an example…
You should see something like this and each time you run it, the result will be different. Note - this doesn’t read the string from Airtable nor does it write the new randomized order back into Airtable. For that we need a little more code and ideally fit to your specific solution.
Script Code
output.markdown("# Shuffle Array");
// create the ordered list
let csvString = "a,b,c,d,e,f,g";
output.markdown("## Ordered List");
output.inspect(csvString);
// parse the string into an array
let myArray = csvString.split(",");
output.markdown("## Ordered Array");
output.inspect(myArray);
// shuffle the array
let myShuffledArray = shuffle(myArray);
output.markdown("## Shuffled Array");
output.inspect(myShuffledArray);
//
// shuffle array
//
function shuffle(array) {
// initialize som needed variables
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
// return the new array
return array;
}
Apr 01, 2020 03:46 PM
Thanks so much, Bill.
I’ll try this out tonight.
Mar 08, 2021 10:41 AM
Hi Bill, can we continue this to include getting the data back into the cell it was copied from?