# App Script to Random Range with 10 % of total data

I have a table with 20 rows of data. I want to randomize the data with 10% of the total data. The script I made is like this:

function shuffleSheet() {
var sheet = ss.getActiveSheet();
var range = sheet.getRange('A2:D21');
range.setValues(shuffleArray(range.getValues()));
}

function shuffleArray(array) {
var i, j, temp;
for (i = array.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}


After I run the script, the results are the data is randomized all the data.

The result what i want, it can see in below :

So you can use something like this

/**
*/
function extractData_(sheet) {
const percent = sheet.getRange('F6').getValue() || 0.1;
const range = sheet.getRange('A3:C');
const values = range.getValues();

const totalData = values.filter(row => row[0] !== '');

const sortIndexes = totalData
.sort(() => 0.5 - Math.random())
.slice(0, parseInt(totalData.length * percent));

sheet
.getRange('L3:N')
.clearContent()
.getSheet()
.getRange(3, 12, sortIndexes.length, sortIndexes[0].length)
.setValues(sortIndexes);
}


Have you considered doing it without resorting to a script, and just using formulas?

For example something along the lines of:  =array_constrain(sort(A2:A23,arrayFormula(randbetween(sign(row(A2:A23)),rows(A2:A23))),TRUE),round(rows(A2:A23)/10),1)  Amending A2:A23 to your actual data etc

• i need random range with app script. Apr 4, 2020 at 19:29