Whenever we want to retrieve or remove certain elements from an array in javascript, splice and slice methods are used.
Slice Method: This method slices(extracts) the array and returns out the new array.
Syntax: array.slice( Start [,end] );
Start: It always starts from zero index from where slicing begins, in case of negative index, start begins from the last of the sequence.
End: It is based on zero index where slicing needs to be stopped.
Return Value: It returns the extracted or sliced array according to the values entered by the users.
Example:
<html>
<head>
<title>JavaScript Array slice Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = ["Plane", "Car", "Bus", "Train", "Truck"];
document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) );
document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) );
</script>
</body>
</html>
Output Snippet:
arr.slice( 1, 2) :Car
arr.slice( 1, 3) :Car, Bus
Splice Method: It is used to make changes in the original array by modifying it where it can take any number of arguments.
<script>
var webDev = ["C", "C++", "Python", "Java"];
document.write(webDev + "<br>");
var removed = webDev.splice(2, 1, 'Node', 'Angular')
document.write(webDev + "<br>");
document.write(removed + "<br>");
// inserting from 2nd, no removing
//ending index
webDev.splice(-2, 0, 'Angular')
document.write(webDev)
</script>
Output:
C, C++, Python, Java
C, C++, Node, Angular,Java
JS
C,C++, Node, React, Angular, Java
Want to become an expert in web technology, check out the Web Development Training offered by Intellipaat.