Skip to content

Instantly share code, notes, and snippets.

@K-Vishwak
Created January 30, 2022 19:20
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 K-Vishwak/7a91e0fd55821b60177f56d949f4f69e to your computer and use it in GitHub Desktop.
Save K-Vishwak/7a91e0fd55821b60177f56d949f4f69e to your computer and use it in GitHub Desktop.
const mainArr = ['apple', 'banana', 'mango', 'grapes', 'orange'];
// start > mainArr.length.
mainArr.splice(5, 1);
> []
// start < mainArr.length to delete on item.
mainArr.splice(1, 1);
> ['banana']
mainArr
> ['apple', 'mango', 'grapes', 'orange']
// add banana again at same location.
mainArr.splice(1, 0, 'banana'); // deleteCount is not optional when items are provided.
> []
mainArr
> ['apple', 'banana', 'mango', 'grapes', 'orange']
// negative offset.
mainArr.splice(-1, 1); // orange will be removed.
> ['orange']
mainArr
> ['apple', 'banana', 'mango', 'grapes']
// no changes to array as 0 elements removed & we are not adding any items to add.
mainArr.splice(1, 0);
> []
mainArr
> ['apple', 'banana', 'mango', 'grapes']
// remove & insert at a time.
mainArr.splice(1, 1, 'newBanana');
> ['banana']
mainArr // banana removed & replaced with newBanana.
> ['apple', 'newBanana', 'mango', 'grapes']
// remove all items from specific index.
mainArr.splice(2);
> ['mango', 'grapes']
mainArr
> ['apple', 'newBanana']
// remove all items.
mainArr.splice(0);
> ['apple', 'newBanana']
mainArr
> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment