Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Array Split in JavaScript

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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]);
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!