-6

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?

AKHIL EM
  • 13
  • 1
  • 4

2 Answers2

2

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)
Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18
  • 3
    Please try avoiding the anser for questions where the user have not done any valid attempts to achieve the result. – Nitheesh Dec 16 '21 at 12:24
  • Although, a `_.groupBy` would be just as effective as that if using LoDash. Plus, the format suggested in my comment on the question would be more useful in terms of passing the data around – Andrew Corrigan Dec 16 '21 at 12:26
-3

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]);
  }
}
Zia
  • 506
  • 3
  • 20