.splice() Method

Use the .splice() method when you want to delete certain elements and/or replace them with other ones.

var darkSide = ['Darth Vader', 'Darth Plagueis', 'Emperor Palpatine', 'Count Dooku', 'General Grievous', 'Kylo Ren', 'Darth Maul'];
var removed = darkSide.splice(2, 4, 'Darth Sidious', 'Darth Tyranus');
console.log(darkSide);
console.log(removed);

Output

[ 'Darth Vader', 'Darth Plagueis', 'Darth Sidious', 'Darth Tyranus', 'Darth Maul' ]
[ 'Emperor Palpatine', 'Count Dooku', 'General Grievous', 'Kylo Ren' ]

Let's break this down:

  • .splice(2) - Start at position 2: 'Emperor Palpatine'

  • .splice(2, 4) - Remove 4 consecutive elements,

  • .splice(2, 4, 'Darth Sidious', 'Darth Tyranus') - add in 'Darth Sidious' and 'Darth Tyranus' (nerds will recognize these as Palpatine and Dooku's Sith names)

  • So what the algorithm is doing is:

    • removing 'Emperor Palpatine' through 'Kylo Ren' (as shown by console.log(removed))

    • replacing them with 'Darth Sidious' and 'Darth Tyranus' (notice that 'Darth Maul' is still the last element)

  • console.log(darkSide) - the true list of canon Sith in Star Wars ('Kylo Ren' is not a Sith in my book)

Last updated