How can I split my array into multiple smaller arrays?

  • A+
Category:Languages

My target is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].

I am using this code:

let arr = [1, 2, 3, 4];  for (let i = 1; i <= arr.length; i++) {   let a = [];   for (let j = 0; j < arr.length; j++) {     a.push(arr[j]);     if (a.length === i) {       break;     }   }   console.log(a); }

And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined

What am I missing/doing wrong?

 


You have two issues in your code:

  1. You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i
  2. You need to remove that break on the length which you have in inner loop.
let arr = [1, 2, 3, 4]; for (let i = 0; i <= arr.length; i++) {   let a = [];   for (let j = i; j < arr.length; j++) {     a.push(arr[j]);     console.log(a);   } }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: