Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 590
IntoTheDeep Avatar asked Sep 17 '18 08:09

IntoTheDeep


People also ask

How do you find the subsequence of a sequence?

A subsequence is just some of the terms of the original sequence, kept in order. If your original sequence is 1,2,3,4,5,6…, one subsequence is 1,3,5,7,9… Another is 1,2343,23565848,8685845855858,… Finding a subsequence is easy. Finding one that does what you want depends on what you want.

Is Subarray contiguous?

A subarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays.

What is the difference between substring and subsequence?

A Substring takes out characters from a string placed between two specified indices in a continuous order. On the other hand, subsequence can be derived from another sequence by deleting some or none of the elements in between but always maintaining the relative order of elements in the original sequence.


3 Answers

For the inner array, you could just start with the index of the outer array.

var array = [1, 2, 3, 4],
    i, j, l = array.length,
    result = [];
    
for (i = 0; i < l; i++) {
    for (j = i; j < l; j++) {
        result.push(array.slice(i, j + 1));
    }
}
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 177
Nina Scholz Avatar answered Oct 21 '22 13:10

Nina Scholz


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);
  }
}
like image 34
Ankit Agarwal Avatar answered Oct 21 '22 13:10

Ankit Agarwal


Try this

 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);            
          }  
        }
like image 42
Alexandr Kudryashov Avatar answered Oct 21 '22 13:10

Alexandr Kudryashov