randomly split array


Recently, I encountered a problem at work. For preparing a training set and testing set for a machine learning problem, I had to randomly split an array into multiple instances. I thought it would be a good idea to document it and make it generalize for future use.

function randSplit(_ary, _percentageSplit) {

// make sure the params are arrays
if(!Array.isArray(_ary) || !Array.isArray(_percentageSplit)) {
console.log(`Both arguments must be of array type`);
return false;

// indeed, logicaly this sum of percentage split should be 100 if(_percentageSplit.reduce((a, b) => a + b, 0) != 100) {
console.log(`Sum of elements of _percentageSplit must be 100, but is `,_percentageSplit.reduce((a, b) => a + b, 0).toString());
return false;

// because we don’t want to modify the original array
_ary = JSON.parse(JSON.stringify(_ary));

// we will populate result object for response
let result = {};
let eleSplit = []
for (let i in _percentageSplit) {
let eleInThisAry = parseInt(_ary.length*_percentageSplit[i]/100);
console.log(`${eleInThisAry.toString()} (${_percentageSplit[i]}% of ${_ary.length}) elements in ${i} object`);

for (let i in _percentageSplit) {
result[i] = [];
while(result[i].length != eleSplit[i]){
result[i].push(_ary.splice(Math.floor(Math.random()*_ary.length), 1)[0])
return result

/* TEST */
let res1 = randSplit([1,2,3,4,5,6,7,8,9,10], [20,30,5]);
// should return false : sum of 2nd argument is not 100
console.log(“res1:: “, res1);

let res2 = randSplit(“[1,2,3,4,5,6,7,8,9,10]”, [20,30,50]);
// should return false : first argument is not an array
console.log(“res2:: “, res2);

let res3 = randSplit([1,2,3,4,5,6,7,8,9,10], [20,30,50]);
// should return proper response
console.log(“res3:: “, res3);

Find updated code at …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s