Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to split array into even chunks?

Marcus
Kilo Contributor

I am seeking to split and array into even chunks of a specific size but having trouble on how to incorporate the .splice() method within my for loop 

  var consumerList = [];
	var cases = new GlideRecord("sn_customerservice_case");
    cases.addQuery('parent', current.sys_id);
    cases.query();
    while (cases.next()) {
        consumerList.push(cases.consumer.email);
        var splitList = consumerList.split(",");
        for (var i = 0; i < splitList.length; i++) {
          gs.print(splitList[i]);
    }
    }
1 REPLY 1

Cris P
Tera Guru

Hi there, can you try something like the below please

  var consumerList = []; // you are defining an array here
    var chunkSize = 100; // add your chunk size
    var cases = new GlideRecord("sn_customerservice_case");
    cases.addQuery('parent', current.sys_id);
    cases.query();
    while (cases.next()) {
        consumerList.push(cases.consumer.email); // you are pushing items to your array
        var splitList = consumerList.split(","); // you are calling split on something that is already an array (is there a need for this?)
        for (var i = 0; i < splitList.length; i++) {
          var chunk = splitList.slice(i, i + chunkSize); // this will be an array of 100 email strings
    }