Extracting a Part of an Array in JavaScript

A part of an array can be extracted with the slice() method. The extracted part is returned as an array. The input array is not changed.

The slice() method accepts two parameters, both optional :

  1. The first parameter defines the start index at which the extraction will begin. The element present at this index is included in the extraction.

    • If no value is provided then the starting index is assumed to be 0.
    • A positive value denotes the index from where extraction begins. If this is greater than the length of the array then an empty array is returned.
    • A negative value implies the starting index is to be calculated from the end of the array.
  2. The second parameter defines the end index before which extraction will stop. Note that extraction will not include element at this index.

    • If no value is provided, the extraction is done till the end of the array.
    • If the value is greater than the length of the array, extraction is carried out till the end.
    • A negative value implies the end index is calculated from the last element of the array.

Demonstrating with a few examples :

// duplicate the array

var array = [1, 2, 3, 4, 5, 6, 7];

var new_array_first = array.slice();

// [1, 2, 3, 4, 5, 6, 7]
console.log(new_array_first);
// extracts all elements starting from the third element

var array = [1, 2, 3, 4, 5, 6, 7];

var new_array_second = array.slice(2);

// [3, 4, 5, 6, 7]
console.log(new_array_second);
// extracts the last element

var array = [1, 2, 3, 4, 5, 6, 7];

var new_array_third = array.slice(-1);

// [7]
console.log(new_array_third);
// extracts all elements excluding the last element

var array = [1, 2, 3, 4, 5, 6, 7];

var new_array_sixth = array.slice(0, -1);

// [1, 2, 3, 4, 5, 6]
console.log(new_array_sixth);
// extracts the third element

var array = [1, 2, 3, 4, 5, 6, 7];

var new_array_first = array.slice(2, 3);

// [3]
console.log(new_array_first);
// extracts 5th and 6th element

var array = [1, 2, 3, 4, 5, 6, 7];

var new_array_fifth = array.slice(-3, -1);

// [5, 6];
console.log(new_array_fifth);