Explain Codes LogoExplain Codes Logo

How to get subarray from array?

javascript
slice-method
array-manipulation
functional-programming
Anton ShumikhinbyAnton Shumikhin·Feb 18, 2025
TLDR

To swiftly create a subarray in JavaScript, apply slice(start, end) method:

let subarray = [1, 2, 3, 4, 5].slice(1, 4); // [2, 3, 4]

Note the start is inclusive while the end is not. The original array remains untouched.

Understanding slice()

The slice(start, end) method serves as a core pillar for manipulating arrays. It births a new array, ensuring your old data remains safe and sound. Let's dig deeper and pull this method apart to optimize its use.

Slice step-by-step: the endIndex

Need a subarray from a specified point up until the end of the array? Exclude the endIndex. JavaScript will decode your intention:

let endSubarray = [1, 2, 3, 4, 5].slice(2); // "I'll take from the third to the end, thank you!"

JavaScript has got your back with slice(), intuitively accommodating unforeseen circumstances.

Slice step-by-step: negative indices

What if you're a rebel and want to use negative indices? Count backwards from the end with slice:

let negativeIndices = [1, 2, 3, 4, 5].slice(-3, -1); // [3, 4] [Read it as "Negative? You're so cool! I gotcha"]

This can spice things up when dealing with operations targeting the tail end of an array.

Slice step-by-step: invalid ranges

slice hands you back an empty array if fromIndex supersedes toIndex, saving your program from disarray:

let invalidRange = [1, 2, 3, 4, 5].slice(4, 2); // [] - because we can't time travel from the future back

This adds an extra layer of protection to your logic especially when you're unsure of the range's origins.

Slice step-by-step: out-of-bounds indices

let outOfBounds = [1, 2, 3].slice(1, 5); // [2, 3] - gives you as much as it can until it runs out

slice() prevents your program from crashing when either start or end points step outside of the array's boundaries.

Anticipating array.length with getSubarray()

You can extend Array.prototype with a custom safety method:

Array.prototype.getSubarray = function(start, end) { return this.slice(start, Math.min(end, this.length)); };

Now, you can use getSubarray to efficiently obtain subarrays even when the end outruns the array's size.

Maintaining the functional approach

To abide by functional programming, strongly resist the urge to modify the original array. This makes your code more predictable and easier to troubleshoot.

Addressing deep copying

Need to clone array objects? Use data structural cloning or apply libraries like Lodash to clone objects residing in the subarray. This dodges any side effects that could occur on complex structures.

Go-to utility: function reuse

Pack getSubarray into its own reusable function:

const getSubarray = (array, start, end) => array.slice(start, end);