I have a JavaScript array as follows
let tasks =[
{id:1,level:1},
{id:1,level:2},
{id:1,level:3},
{id:2,level:1},
{id:2,level:2},
{id:3,level:1}]
I want to split this array into
let tasks =[
[{id:1,level:1},
{id:1,level:2},
{id:1,level:3}],
[{id:2,level:1},
{id:2,level:2}],
[{id:3,level:1}] ]
How to do this?
You can do it by using reduce helper, like this:
const tasks =[
{id:1,level:1},
{id:1,level:2},
{id:1,level:3},
{id:2,level:1},
{id:2,level:2},
{id:3,level:1}];
const newTasks = tasks.reduce((acc, data)=> {
const target = acc.find(subArr => subArr.find(item => item.id == data.id));
target ? target.push(data) : acc.push([data]);
return acc;
} , []);
console.log(newTasks)
You can write a loop to iterate through this array, push half to a and half to b.
a=[]; b=[];
for(int i=0;i<tasks.length;i++){
if(i<=tasks.lenght/2){
a.push(tasks[i]);
}else{
b.push(tasks[i]);
}
}