Search

How to slice from array in JavaScript?

  • Share this:

To slice an array in JavaScript, you can use the `Array.prototype.slice()` method. This method returns a shallow copy of a portion of an array into a new array object, without modifying the original array.

The `slice()` method takes two arguments: the start index (inclusive) and the end index (exclusive). It returns all the elements from the start index to the end index as a new array.

Here is an example of how to use the `slice()` method to slice an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sliced = numbers.slice(2, 5);
console.log(sliced);  // [3, 4, 5]

In this example, the `slice()` method returns a new array containing the elements at index 2, 3, and 4 of the original array (elements 3, 4, and 5).

You can also use negative indices with the `slice()` method. If you specify a negative index, it is counted from the end of the array. For example:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sliced = numbers.slice(-5, -2);
console.log(sliced);  // [6, 7, 8]

In this example, the `slice()` method returns a new array containing the elements at index 5, 6, and 7 of the original array (elements 6, 7, and 8).

If you want to slice the array from a given index to the end of the array, you can omit the second argument. For example:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sliced = numbers.slice(4);
console.log(sliced);  // [5, 6, 7, 8, 9, 10]

In this example, the `slice()` method returns a new array containing all the elements from index 4 to the end of the original array (elements 5, 6, 7, 8, 9, and 10).

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.