Array splice()

splice() inserts items into the middle of an array. splice() can do three things to an array:Deletion, Insertion and Replacment

Deletion

Items can be deleted from the array by specifying just two arguments:

  • the position of the first item to delete and
  • the number of items to delete.

For example, splice(0, 2) deletes the first two items.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C", "D", "E"]; 
        var colors2 = colors.splice(0,2); 
        document.writeln(colors); //C,D,E
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

Insertion

Items can be inserted into a specific position by providing three or more arguments:

  • the starting position,
  • 0,
  • any number of items to insert.

0 means deleting zero number of items from the array. You can specify a fourth parameter, or any number of other parameters to insert.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C", "D", "E"]; 
        var colors2 = colors.splice(2,0,"A","B","C"); 
        document.writeln(colors); //A,B,A,B,C,C,D,E
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

Replacement

Items can be inserted and deleted with three arguments:

  • the starting position,
  • the number of items to delete,
  • any number of items to insert.

The number of items to insert doesn't have to match the number of items to delete.

splice(2, 1, "A", "B") deletes one item at position 2 and then inserts the strings "A" and "B" at position 2. splice() returns an array with removed items or empty array if no items were removed.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C"]; 
        var removed = colors.splice(1, 1, "D", "E"); //insert two values, remove one 
        document.writeln(colors); //A,D,E,C
        document.writeln(removed); //B
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Essential Types  

Array:
  1. The Array Type
  2. Array Built-in Methods
  3. Detecting Arrays
  4. Get and set array values
  5. Enumerating the Contents of an Array
  6. Array Length
  7. Array join() method
  8. Array concat()
  9. Array indexOf()
  10. Array lastIndexOf()
  11. Array every()
  12. Array filter() filters array with the given function.
  13. Array map()
  14. Array forEach()
  15. push() and pop():Array Stack Methods
  16. push(), shift():Array Queue Methods
  17. Array reduce()
  18. Array reduceRight()
  19. reverse():Reordering array
  20. Array slice()
  21. Array some()
  22. Array splice()
  23. Array sort()
  24. toString(), toLocaleString() and valueOf Array
  25. Array unshift()