JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  1. 05-Arrays
  2. Array Methods

.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)

Previous.replace() MethodNext.map() Method

Last updated 7 years ago