JS: slice() Method

Advertisements
Advertisements

 19 total views

The slice() method is part of JavaScript Array class. It extract certain elements from an array and returns a new array.

There are different ways to select elements using slice() in JavaScript.

The slice() method takes two parameters – start index and the end index of an array. It does not include the last element while returning a new array.

Examples of slice() method

In these examples, we will extract from an array using different forms of slice() syntax.

Advertisements
// declare the array
myArray = ["one", "two", "three", "four"];
// only start index is mentioned
var result1 = myArray.slice(2);
console.log(result1);

The slice() method will start extracting from index 2 and since the end index is not mentioned, it will extract the rest of elements from the array. The result of the above program is given below.

["three", "four"]

In the next example, we will mention both start as well as end index value. Here is the example script.

// declare the array
myArray = ["one", "two", "three", "four"];
// both start index and end index is mentioned
var result = myArray.slice(1,3);
console.log(result);

The array start with index 1 of the array. At index 1, the element is “two” and ends with index 2 because the end value 3 in slice(1,3) is not included.

The output is as follows.

Sometimes you want to extract elements starting from end to start of the array. It is also known as negative index.

// declare the array
myArray = ["one", "two", "three", "four"];
// negative index starts from -1
var result = myArray.slice(-3,-1);
document.body.innerHTML = result;

The negative index starts from -1. The element at -1 position is “three” in the above example array.

You cannot use index 0 because it is a positive index and starts from beginning of the array.

The output of the above code is as follows.

two,three
Advertisements
Advertisements
Advertisements