Open In App

JavaScript Array slice() Method

The Array slice() method in JavaScript returns selected elements from an array, creating a new array. It selects elements from a specified start index up to, but not including, a specified end index. The original array remains unchanged.

Array slice() Syntax

arr.slice(begin, end);

Array slice() Parameters

Array slice() Return value

This method returns a new array containing some portion of the original array. 



Array slice() Method Examples

Example 1: Extracting elements between two indexes

Here, the slice() method extracts the array from the given array starting from index 2 and including all the elements less than index 4.




function func() {
    // Original Array
    let arr = [23, 56, 87, 32, 75, 13];
    // Extracted array
    let new_arr = arr.slice(2, 4);
    console.log(arr);
    console.log(new_arr);
}
func();

Output

[ 23, 56, 87, 32, 75, 13 ]
[ 87, 32 ]





Explanation

Example 2: Passing no arguments

Here, the slice() method extracts the entire array from the given string and returns it as the answer, Since no arguments were passed to it.




function func() {
    //Original Array
    let arr = [23, 56, 87, 32, 75, 13];
    //Extracted array
    let new_arr = arr.slice();
    console.log(arr);
    console.log(new_arr);
}
func();

Output
[ 23, 56, 87, 32, 75, 13 ]
[ 23, 56, 87, 32, 75, 13 ]





Explanation

Example 3: Extracting array from index 2

In this example, the slice() method extracts the array starting from index 2 till the end of the array and returns it as the answer.




function func() {
    //Original Array
    let arr = [23, 56, 87, 32, 75, 13];
    //Extracted array
    let new_arr = arr.slice(2);
    console.log(arr);
    console.log(new_arr);
}
func();

Output
[ 23, 56, 87, 32, 75, 13 ]
[ 87, 32, 75, 13 ]





Explanation

Example 4: Slicing the nested Array

In this example, the slice() method extracts the elements from the nested array and returns it as the answer.




function func() {
    // Original Array
    let arr = [23, [87, 32, 75, 27,3,10,18 ,13]];
    // Extracted array
    let new_arr = arr[1].slice(2, 4);
    console.log(arr);
    console.log(new_arr);
}
func();

Output

[23, [87, 32, 75, 27,3, 10, 18, 13 ]]
[ 75, 27 ]

Explanation

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers


Article Tags :