Skip to content

Instantly share code, notes, and snippets.

@svapreddy
Created July 17, 2014 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svapreddy/e01a84279f1789133b85 to your computer and use it in GitHub Desktop.
Save svapreddy/e01a84279f1789133b85 to your computer and use it in GitHub Desktop.
/*
Here are few ways to use slice for different use cases.
I am just adding few regular usecases I am able to recollect at this point of time. Will add more later.
*/
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
// Traditional use.
arr.slice(0, 2); // result is [1, 2]
arr.slice(0, 3); // result is [1, 2, 3]
arr.slice(0, 8); // result is [1, 2, 3, 4, 5, 6, 7, 8]
arr.slice(0, 9); // result is [1, 2, 3, 4, 5, 6, 7, 8]
// If you observe immediate above line, it's taking second param as length when it exceeds length.
// Now lets use slice for some other purposes.
// Find last item in array
var lastItemInArr = arr.slice(-1).pop(); // result will be 8.
// The above line is equivalant to arr[arr.length-1];
// Lets clone an array
var arrClone = arr.slice(0) // result will be [1, 2, 3, 4, 5, 6, 7, 8];
/*
The above line is equivalant to below approaches.
method 1 :
var arrClone = [].push.apply([], arr);
method 2 :
var arrClone = [];
for(var i = 0, l = arr.length; i < l; i++){
arrClone.push(arr[i]);
}
*/
// Lets find last n items in an array
var lastNItems = arr.slice(Math.max(arr.length - n, 1)); @// Thanks to SLaks in SO
// Find first n items in an array
var firstNItems = arr.slice(0, n); // for this requirement Math.min check is not required. Refer above lines to know why.
// And some other experiments
arr.slice(-2) // result will be [7, 8];
arr.slice(-3) // result will be [6, 7, 8];
arr.slice(-7) // result will be [2, 3, 4, 5, 6, 7, 8];
arr.slice(0) // clone of the array as I have mentioned above. I hope you understood how slice(0) works.
arr.slice(-100) // it will also give clone of the array because "100 is greater than the arr length"
// From above lines you may understand that you can use negative values to find last items.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment