OneBite.Dev - Coding blog in a bite size

extract a sub-array from an array in Javascript

Code snippet on how to extract a sub-array from an array in Javascript

  var array = [1,2,3,4,5];
  var subArray = array.slice(1, 4)

This code extracts a sub-array from an array given in Javascript. First, it declares a variable called ‘array’, and assigns it to an array of elements [1,2,3,4,5]. Then, it declares another variable called ‘subArray’, and assigns it to a portion of the original array using the slice() method. The slice() method takes two parameters, the starting index and the end index (exclusive). In this example, the starting index is 1 and the end index is 4. Therefore, this code assigns the subArray variable to the elements from 1 to 3, which is [2,3,4].

javascript