JS Array Slice & Splice

Array slice()

The slice() method returns selected elements in an array, as a new array.

The slice() method selects from a given start, up to a (not inclusive) given end.

The slice() method does not change the original array.

Syntax

array.slice(start, end)

Parameters

Parameter Description
start Optional.
Start position. Default is 0.
Negative numbers select from the end of the array.
end Optional.
End position. Default is last element.
Negative numbers select from the end of the array.
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Sanjay", "Aman", "Rehman","Rahul", "Karan"];
    document.write(a + "<br><br>");
    var b = a.slice(1 , 4);
    document.write(b);
  </script>
</head>
<body>

</body>
</html>

 


Array splice()

The splice() method adds and/or removes array elements.

The splice() method overwrites the original array.


Syntax

array.splice(index, howmany, item1, ....., itemX)

Parameters

Parameter Description
index Required.
The position to add/remove items.
Negative value defines the position from the end of the array.
howmany Optional.
Number of items to be removed.
item1, ..., itemX Optional.
New elements(s) to be added.
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Sanjay", "Aman", "Rehman", "Rahul"];
    document.write(a + "<br><br>");
    a.splice(2,0,"Neha","Karan");
    document.write(a);
  </script>
</head>
<body>

</body>
</html>