Extract sub-array from an array in javascript

You can use the slice() method in JavaScript to get a sub-array from an array. Here’s a simple example:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let subArray = array.slice(3, 7);
console.log(subArray);  // This will output [4, 5, 6, 7]

In this example, the slice() method takes two arguments: the start index and the end index. The start index is inclusive, and the end index is exclusive. So array.slice(3, 7) returns a new array starting from the 4th element (index 3) up to (but not including) the 8th element (index 7) of the original array.

Please note that JavaScript array’s index is 0-based. That means the first item of the array is at index 0, the second item is at index 1, and so on.

The slice() method does not modify the original array, it returns a new array. If you want to modify the original array, you can use the splice() method instead.

Leave a Reply

Your email address will not be published. Required fields are marked *