DEV Community

Cover image for Array Slicing
Sakshi
Sakshi

Posted on

4 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more