Nitish Nitish - 1 year ago 153
Javascript Question

Typescript - array to chunks

I have an array as following:

public taskListCustom: any=[
{title: 'Task 1', status: 'done'},
{title: 'Task 2', status: 'done'},
{title: 'Task 3', status: 'done'},
{title: 'Task 4', status: 'done'},
{title: 'Task 5', status: 'done'},
{title: 'Task 6', status: 'done'},
{title: 'Task 7', status: 'done'},
{title: 'Task 8', status: 'done'},
{title: 'Task 9', status: 'done'},
{title: 'Task 10', status: 'done'},
{title: 'Task 11', status: 'done'},
{title: 'Task 12', status: 'done'},
{title: 'Task 13', status: 'done'},
{title: 'Task 14', status: 'done'},
{title: 'Task 15', status: 'done'},
{title: 'Task 16', status: 'done'},
{title: 'Task 17', status: 'done'},
{title: 'Task 18', status: 'done'},
{title: 'Task 19', status: 'done'},
{title: 'Task 20', status: 'done'},
{title: 'Task 21', status: 'done'},
{title: 'Task 22', status: 'done'},
{title: 'Task 23', status: 'done'},
{title: 'Task 24', status: 'done'},
]


And another empty array:
public taskListCustomChunked: any=[];


My goal is: if I get chunk size say of 6 (this number can be anywhere between 4 to 11) then I have to chop taskListCustom into 6 arrays (i.e. 24/6=4) and then insert each chunk as an array into taskListCustomChunked i.e. it will look something like:

taskListCustomChunked = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[..],[..]]


How can I accomplish it?

Answer Source

You can achieve this using slice method.

let taskListCustom=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task 4', status: 'done'}, {title: 'Task 5', status: 'done'}, {title: 'Task 6', status: 'done'}, {title: 'Task 7', status: 'done'}, {title: 'Task 8', status: 'done'}, {title: 'Task 9', status: 'done'}, {title: 'Task 10', status: 'done'}, {title: 'Task 11', status: 'done'}, {title: 'Task 12', status: 'done'}, {title: 'Task 13', status: 'done'}, {title: 'Task 14', status: 'done'}, {title: 'Task 15', status: 'done'}, {title: 'Task 16', status: 'done'}, {title: 'Task 17', status: 'done'}, {title: 'Task 18', status: 'done'}, {title: 'Task 19', status: 'done'}, {title: 'Task 20', status: 'done'}, {title: 'Task 21', status: 'done'}, {title: 'Task 22', status: 'done'}, {title: 'Task 23', status: 'done'}, {title: 'Task 24', status: 'done'}, ]
let chunkLength= 3;
let chunkSize=taskListCustom.length/chunkLength;
let result=[];
for (i=0; i<taskListCustom.length; i+=chunkSize) {
    result.push(taskListCustom.slice(i,i+chunkSize).map(a=>a.title));
}
console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download