DEV Community

Cover image for Array Slicing
Sakshi
Sakshi

Posted on

Array Slicing

Array slicing involves taking a subset from an array and allocating a new array with those elements.

In JavaScript you can create a new array of the elements in myArray, from startIndex to endIndex (exclusive), like this:

  myArray.slice(startIndex, endIndex);
Enter fullscreen mode Exit fullscreen mode

You can also get everything from startIndex onwards by just omitting endIndex:

  myArray.slice(startIndex);
Enter fullscreen mode Exit fullscreen mode

Careful: there's a hidden time and space cost here! It's tempting to think of slicing as just "getting elements," but in reality you are:❗❗❗

Allocating a new array

Copying the elements from the original array to the new array
This takes O(n)O(n) time and O(n)O(n) space, where nn is the number of elements in the resulting array.

That's a bit easier to see when you save the result of the slice to a variable:

const tailOfArray = myArray.slice(1);

But a bit harder to see when you don't save the result of the slice to a variable:

  return myArray.slice(1);
// Whoops, I just spent O(n) time and space!

  myArray.slice(1).forEach(item => {
  // Whoops, I just spent O(n) time and space!
});

Enter fullscreen mode Exit fullscreen mode

So keep an eye out. Slice wisely.🧐

Top comments (0)