Home > database >  How to go about making an array of the items between two keywords of another array?
How to go about making an array of the items between two keywords of another array?

Time:10-21

Sounds way more confusing than it actually is, but it is simple given an example:

Let's say I have an array like this - [1, 2, 3, 4, 5]

I want the numbers 2, 3 and 4 in their own array like this - [2, 3, 4]

One detail is that the array is completely random! It is all user inputted so I use keywords to find the section I want, like this - ["cmd", "|arg", "stuff", "blah", "|end"]

For this example I would like an array of the items between the keywords |arg and |end that looks like this - ["stuff", "blah"]

I have already found the position in the array of the two keywords but how would I go about making an array of the items between these keywords?

I have tried splicing and I have tried for, but for is not allowed in the game I am coding for and I just cannot seem to find out how to splice it. There has to be a better way and I am not sure what the Method would be called if there even is a Method that can accomplish this.

I don't have any real code to show, as it would be a complete and utter mess if I show it

Just started learning javascript 3 days ago

CodePudding user response:

If you first check to see if that the array contains both values, then you can slice the array into another result array.

let ar = ["cmd", "|arg", "stuff", "blah", "|end"];
let arRes = [];

if(ar.includes("|arg") && ar.includes("|end")){
  let idx1 = ar.indexOf("|arg")   1;
  let idx2 = ar.indexOf("|end");
  arRes = ar.slice(idx1, idx2)
}

console.log(arRes)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related