JavaScript Array slice() method
JavaScript Array slice() method is used to slice an Array from given start index upto given end index.
Syntax
The syntax to call call() method on an array x
is
</>
Copy
x.slice(2, 5)
where start=2, and end=5.
slice() method returns a new array, and the original array remains unmodified.
Examples
In the following example, we take an array of numbers, and slice the array from index=2 upto index=5 using slice() method.
index.html
<!doctype html>
<html>
<body>
<pre id="output"></pre>
<script>
var x = [2, 4, 6, 8, 10, 12, 14, 16];
var result = x.slice(2, 5);
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
In the following example, we take an array of strings, and slice the array from index=1 upto index=5 using slice() method.
index.html
<!doctype html>
<html>
<body>
<pre id="output"></pre>
<script>
var x = ['apple', 'ball', 'car', 'dome', 'egg', 'fist'];
var result = x.slice(1, 4);
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we have learnt how to use slice() method to slice an Array and get sub-array.