Posts

Showing posts with the label substring

How to get all substrings (contiguous subsequences) of my JavaScript array?

My task 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: 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 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); } } For the inner array, you could just start with...