Typescript - 数组到块

时间:2017-10-02 12:14:50

标签: javascript angular typescript

我有一个如下数组:

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'},
]

另一个空数组:public taskListCustomChunked: any=[];

我的目标是:如果我得到的块大小为6(这个数字可以在4到11之间),那么我必须将taskListCustom分成6个数组(即24/6 = 4),然后将每个块插入数组到taskListCustomChunked即它看起来像:

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

我怎样才能完成它?

1 个答案:

答案 0 :(得分:5)

您可以使用slice方法实现此目的。

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= 7;
let chunkSize=Math.round(taskListCustom.length/chunkLength);
let result=[];
for (i=0; i<taskListCustom.length; i+=chunkSize) {
    if(result.length<chunkLength-1)
      result.push(taskListCustom.slice(i,i+chunkSize).map(a=>a.title));
    else{
      result.push(taskListCustom.slice(i).map(a=>a.title));
      break;
    }
}
console.log(result);