How to Extract JavaScript Array Elements From Start to End Index?

You can extract a portion of a JavaScript array from/to an index by using the Array.prototype.slice() method, for example, like so:

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

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

This will extract elements of the array starting from index 2 up to, but not including, index 5 from the originalArray, as you can see in the illustration below:

array:       [ 1     2     3     4     5     6     7     8     9 ]
               |     |     |     |     |     |     |     |     |
index:         0     1     2     3     4     5     6     7     8

slice(2, 5):               |___________|

The Array.prototype.slice() method does not modify the original array. Instead, it returns a shallow copy of the portion of the array as a new array, as you can see in the following example:

const originalArray = [1, 2, 3, 4];
const newArray = originalArray.slice(1, 4);

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

If you wish to modify the original array in-place, then you can use methods like Array.prototype.splice().

If you want to extract elements from a specific index to the end of the array, you can omit the second parameter:

const originalArray = [1, 2, 3, 4];
const newArray = originalArray.slice(1);

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.