How to get subarray from array?
To swiftly create a subarray in JavaScript, apply slice(start, end)
method:
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:
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
:
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:
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
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:
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:
Was this article helpful?