1

How do I make a variable equal to every item between 2 items in an array? So it would only make the variable contain the items in the array that are above the place 0 in the list.

An example of what I mean is this: let message = array[1, array.length]

So in an array like this ["dog", "cat", "fish", "snake", "elephant"] if it was to be printed to the console it would print cat, fish, snake and elephant

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
bob digby
  • 37
  • 6
  • 3
    MDN: [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) – p.s.w.g Feb 06 '19 at 22:48
  • 2
    Possible duplicate of [split an array into two based on a index in javascript](https://stackoverflow.com/questions/6872630/split-an-array-into-two-based-on-a-index-in-javascript) or [Javascript Array: get 'range' of items](https://stackoverflow.com/q/3580239/215552) – Heretic Monkey Feb 06 '19 at 22:51

1 Answers1

1

What you are after is splice() and split(). I have added a demo for you below:

var arr = ["dog", "cat", "fish", "snake", "elephant"];

// Array.splice() will take everything at / after the index you specify
console.log(arr.slice(1)); // ['cat','fish','snake','elephant']

// array.splice will show everything located on or between the index you specify.
console.log(arr.splice(1,3)); // ['cat', 'fish', 'snake']
Spangle
  • 762
  • 1
  • 5
  • 14