How to Get A SubArray From An Array In JavaScript – Definitive Guide

Arrays are used to store multiple elements in a single object.

You can get a subarray from an array in JavaScript using the array.slice() method.

Basic Example

var myArray = [1, 2, 3, 4, 5];  // Get a subarray with elements at indices 1 and 2 (inclusive)

var subArray = myArray.slice(1, 3);  

console.log(myArray); // [1, 2, 3, 4, 5]

console.log(subArray); // [2, 3]
  • Creates a subarray from the elements in the range of the start and end indexes specified.
  • Doesn’t mutate the original array

This tutorial teaches you how to create a subarray from an array in JavaScript.

Array.slice() method

The Array.slice() method creates a subarray based on the elements in the start and end index specified.

  • It doesn’t mutate the original array.
  • Creates a new shallow copy of the array.

Use this method when you want to create a subarray based on the range of index positions in the original array and don’t want to modify the original array.

Code

var myArray = [1, 2, 3, 4, 5];  // Get a subarray with elements at indices 1 and 2 (inclusive)

var subArray = myArray.slice(1, 3);  

console.log(myArray); // [1, 2, 3, 4, 5] - Original array remains the same

console.log(subArray); // [2, 3] - New subarray is created with the elements

Array.splice() method

The Array.splice() method allows you to change the array by removing or replacing the original array.

  • When you pass the start index and a number of elements to delete, it’ll remove the number of items starting from the index and returns a new array with those elements.
  • It mutates the original array.

Use this method when you want to remove some elements from the original array and create a sub-array from the removed elements.

Code

var myArray = [1, 2, 3, 4, 5];  // Get a subarray with elements at indices 1 and 2 (inclusive) 

var subArray = myArray.splice(1, 3);  

console.log(myArray); // [1, 5]

console.log(subArray); // [2, 3, 4]

Array.filter() method

The Array.filter() method allows you to create a subarray based on a specific condition.

  • Filters the items that pass the specific condition
  • Returns a new array with the filtered elements. Doesn’t mutate the original array.

Use this method when you want to create a sub-array with elements that pass a specific condition.

Code

Use the following code to create an array with elements greater than 3.

var myArray = [1, 2, 3, 4, 5]; 

const subArray = myArray.filter(x => x >3);

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

Additional Resources

Leave a Comment