How to make group of Array

Hello Developers, I have an array is [1,5,6,7,8,5,9,33,45,65,11,21],

I am trying to make it as like as [[1,5,6],[7,8,5],[9,33,45],[65,11,21]];

I have done by the following code but it is not working.

const pendu=(arr)=>{

  const possibleLoop=arr.length/3;
  let start=0;
  let results=[];
  let loop=3;
  let count=0;
  
 for(start; start<loop; start++){
   
   let newArr=[x].concat(arr[start]);
   
   results.push(newArr);
   
   count++;
   if(count % 3 === 0){
     //console.log("done")
     loop=loop+3;
   }
   if(count > arr.length){
     break;
   }
 }

   return results;
   
}




console.log(pendu([1,5,6,7,8,5,9,33,45,65,11,21]))

I am just got stuck here, any suggestion ?

For future reference, you need to wrap any code you post here with triple backticks. If you don’t know how to do that then click the </> button at the top of this editor and it will provide them for you.

I’m not crazy about how you are doing the for loop. Changing the value of loop does not seem like a great idea to me. Most people would expect that to remain the same. My recommendation would be to redo your for loop logic so that the only value that is changing is start. I also think this change will make your logic inside the loop easier. Perhaps there is an array method that can help you slice out the items you want each time you iterate through the for loop?

sorry updated. Apologies

Not an answer to the specific problem, but when reviewing JavaScript methods available to you to solve this, I highly recommend: https://devdocs.io

I’ve been using it for years now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.