eclipseIzHere eclipseIzHere - 6 months ago 28
Javascript Question

Choosing multiple items in array

I have an array,

var arr=[1,2,3,4,5,6,7,8,9,10];

I don't know how long the array is, and I want to select everything after 3. How do i do that?


In your example, the "3" is located in the slot for index two. If you want everything after the third element (index two) the first function will do that.

If you want everything after the first 3 found, then the second function will do that.

// This finds all content after index 2
Array.prototype.getEverythingAfterIndexTwo = function() {
  if (this.length < 4) { 
    return [];
  } else {
    return this.slice(3);

// This finds the first 3 in the array and returns any content in later indices
Array.prototype.getEverythingAfterAThree = function() {

  // returns array if empty
  if (!this.length) return this;  

  // get the index of the first 3 in the array
  var threeIndex = this.indexOf(3);

  // if no 3 is found or 3 is the last element, returns empty array
  // otherwise it returns a new array with the desired content
  if (!~threeIndex || threeIndex === this.length-1) {         
      return [];
  } else {
      return this.slice(threeIndex + 1);

var arr=[1,2,3,4,5,6,7,8,9,10];