Slice is a powerful method that allows you to extract a portion of an array and create a new array with the extracted elements. It doesn't modify the original array.
Key Concepts:
- Start index: Specifies the index of the first element to be included in the new array.
- End index (exclusive): Specifies the index of the first element to be excluded from the new array.
Steps Involved:
- Identify the start and end indices: Determine which elements you want to extract.
- Use the slice() method: Pass the start and end indices as arguments to the slice() method:
array.slice(start, end)
- Assign to a new variable: Store the result in a new variable to create the new array.
JavaScript Example:
const originalArray = [1, 2, 3, 4, 5];
// Extract elements from index 1 (inclusive) to index 4 (exclusive)
const newArray = originalArray.slice(1, 4);
console.log(newArray); // Output: [2, 3, 4]