bellatrix

Sakshi

Posted on March 3, 2022

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.🧐

πŸ’– πŸ’ͺ πŸ™… 🚩
bellatrix
Sakshi

Posted on March 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript: Look! Loops!
javascript JavaScript: Look! Loops!

February 23, 2023

Array Slicing
javascript Array Slicing

March 3, 2022

Data Structures with JavaScript: Stacks
javascript Data Structures with JavaScript: Stacks

September 30, 2019

Data Structures with JavaScript: Queues
javascript Data Structures with JavaScript: Queues

January 6, 2020