Skip to content

Instantly share code, notes, and snippets.

@vishalkukreja
Created March 31, 2021 14:55
Show Gist options
  • Save vishalkukreja/52aa803b8de5c6e31d7eabb34868f00c to your computer and use it in GitHub Desktop.
Save vishalkukreja/52aa803b8de5c6e31d7eabb34868f00c to your computer and use it in GitHub Desktop.
//slice() example
var cityNames = ['Mumbai', 'Delhi', 'Pune', 'Ahmadabad', 'Indore'];
console.log("City names:", cityNames);
// Output : City names: [ 'Mumbai', 'Delhi', 'Pune', 'Ahmadabad', 'Indore' ]
var newCities = cityNames.slice(); // gets all - shallow copy
console.log(newCities); //[ 'Mumbai', 'Delhi', 'Pune', 'Ahmadabad', 'Indore' ]
var newTwoCities = cityNames.slice(1, 3); // start from 1st index and before 3rd
console.log(newTwoCities); //[ 'Delhi', 'Pune' ]
var remainingCities = cityNames.slice(1); // start from 1st index and extract rest
console.log(remainingCities); //[ 'Delhi', 'Pune', 'Ahmadabad', 'Indore' ]
// If start is greater than the index or negative, an empty array is returned.
var otherCities = cityNames.slice(-1, 3); //cityNames.slice(5, 4);
console.log(otherCities); // []
var initialCities = cityNames.slice(0, -2); //extract from the start/remove from end
console.log(initialCities); // [ 'Mumbai', 'Delhi', 'Pune' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment