How to Create an Array from a Specific Index to Another Index in JavaScript?

Estimated read time 1 min read

To create an array from a specific index to another index in JavaScript, you can use the slice() method. The slice() method returns a shallow copy of a portion of an array into a new array object selected from startIndex to endIndex (endIndex is not included).

Here’s an example code snippet that demonstrates how to create an array from a specific index to another index in JavaScript:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const startIndex = 2;
const endIndex = 6;
const newArray = array.slice(startIndex, endIndex);

console.log(newArray); // [2, 3, 4, 5]

In this code, we have an array array containing 10 elements. We want to create a new array from the index 2 to 6. To achieve this, we have used the slice() method on the array and passed the startIndex and endIndex as its arguments. The slice() method returns a new array containing elements from index 2 to index 6-1=5 (i.e., [2, 3, 4, 5]) and assigned it to a new variable called newArray.

Note that the slice() method doesn’t modify the original array, but returns a new array that contains the specified portion of the original array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply