Skip to content

Instantly share code, notes, and snippets.

@theankitgaurav
Last active November 17, 2016 07:12
Show Gist options
  • Save theankitgaurav/6e930007e7a2143683b9d2e8a0df230e to your computer and use it in GitHub Desktop.
Save theankitgaurav/6e930007e7a2143683b9d2e8a0df230e to your computer and use it in GitHub Desktop.
Some js array utility methods

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

var a = [1, 2, 3];
a.shift();

console.log(a); // [2, 3]

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

var a = ["zero", "one", "two", "three"];
var sliced = a.slice(1,3);

console.log(a);      // [ "zero", "one", "two", "three" ]
console.log(sliced); // [ "one", "two" ]

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(2, 0, "drum"); 

// myFish is ["angel", "clown", "drum", "mandarin", "surgeon"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment