close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

JS Array Slice Explained

JS Array Slice Explained
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Learn how to use the slice() method in JavaScript to create new arrays, extract segments, and work with array-like objects efficiently. Find examples and common use cases here!

The slice() method in JavaScript is a powerful tool for working with arrays. It lets you create a new array by extracting a segment of another array without altering the original. Here's a quick overview:

  • Creates a new array from a segment of another array.
  • Does not modify the original array, keeping it intact.
  • Flexible selection with start and end parameters; use negative numbers to count from the end.
  • Shallow copy: For arrays of objects, only the references are copied, not the objects themselves.
  • Useful for various tasks like copying an array, extracting parts of an array, or even removing elements indirectly.

Understanding slice() helps you manipulate array data efficiently, whether you need a portion of the array or to work with array-like objects in a more array-friendly manner.

Return Value

The slice() method gives you a new array with the pieces you chose.

Basic Usage

Here are a few simple ways to use slice():

// Copy the whole array
let arrCopy = arr.slice() 

// The first 3 items
let first3 = arr.slice(0, 3)

// The last 2 items
let last2 = arr.slice(-2) 

Slice() is handy for making a copy of an array, taking out specific parts, and more, all without changing the original.

Working with Negative Indexes

Negative indexes let you start slicing an array from the end, which is handy for grabbing the last elements without knowing their exact positions.

Slicing from the End

To get the last item of an array, you can use -1 like this:

const arr = [1, 2, 3, 4];

const lastElement = arr.slice(-1); // [4]  

And if you want more than one item from the end, just use a bigger negative number:

const arr = [1, 2, 3, 4, 5];

const last3Elements = arr.slice(-3); // [3, 4, 5]

Specifying Negative Start and End

You can slice a middle section from the end by using both a negative start and end index:

const arr = [1, 2, 3, 4, 5];

const slice = arr.slice(-4, -2); // [2, 3]

Here, we started slicing from the fourth item from the end (which is 2) and stopped before the second item from the end (which is 4).

Using negative indexes with slice() makes it easy to take parts from the end of an array without needing to count the exact spots.

Slicing Arrays of Objects

When you use the slice() method on an array that has objects, it just copies the way to reach those objects into a new array. It doesn't create brand new, separate objects. This is called a shallow copy.

Object Reference Behavior

Imagine you have an array of objects, and you make a sliced copy of this array. If you change something in an object from the sliced array, this change will show up in the original array too. That's because both the original and sliced arrays are looking at the same objects.

For example:

const objects = [{id: 1}, {id: 2}, {id: 3}];

const sliced = objects.slice();

sliced[0].id = 5; 

console.log(objects[0].id); // 5

In this case, changing the id of the first object in the sliced array also changes it in the original array, because they are both connected to the same object.

Alternatives for Deep Copy

If you want to make a copy of an array of objects where changes in the copy don't affect the original, you can use other methods like spread syntax or JSON parsing. These methods create completely separate objects, so changes in one don't show up in the other.

// Spread syntax
const deepCopy = [...objects];

// JSON parse/stringify
const deepCopy = JSON.parse(JSON.stringify(objects)); 

Using these methods, you can edit the objects in the new array without worrying about the original array.

sbb-itb-bfaad5b

Common Use Cases

Let's look at some everyday situations where slice() comes in handy.

Extracting a Portion of an Array

Think of slice() as a way to pick out a specific part of a list (array) without messing up the original list. For example, if you have a list of numbers and just want the first 10, you can do this:

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const first10 = items.slice(0, 10); 

This method is perfect when you need a smaller piece of a bigger list for something else. And the best part? The original list stays the same.

Removing an Element

If you need to take out something from the middle of a list, slice() can help. You cut the list into two around the item you don't want, then stick the pieces back together:

const arr = [1, 2, 3, 4, 5];

// Remove index 2 (the 3)
const newArr = arr.slice(0, 2).concat(arr.slice(3)); 

console.log(newArr); // [1, 2, 4, 5]

This way, you get a new list without the item you wanted to remove.

Converting Array-like Objects

Sometimes, you get things that look like lists but aren't quite there, like the arguments object in functions. You can turn these into real lists using slice():

function printArgs() {
  const argsArr = Array.prototype.slice.call(arguments);
  
  argsArr.forEach(arg => console.log(arg)); 
}

printArgs(1, 2, 3);

This trick changes the arguments object into a list you can work with, like looping through the items. It's a handy move when dealing with list-like objects.

Conclusion

The slice() method is really handy when you're working with lists (arrays) in JavaScript. It's like using a pair of scissors to cut out exactly what you need from a list and put it into a new one. Here's what makes slice() so useful:

  • It can take a small part of a list and make a new list out of it.
  • You can choose where to start and stop cutting.
  • It can count backwards, so you can start cutting from the end of the list.
  • It doesn't mess up the original list.
  • When cutting lists that have things like objects in them, it just copies the way to find those things, not the things themselves.

Here are some common times you might want to use slice():

  • When you need a part of a list for something else.
  • When you want to remove something from a list without ruining the whole thing.
  • When you have something that's almost a list but not quite, and you need it to be a real list.

Slice() is perfect for getting parts of a list without changing the original. Just tell it where to start and stop, and it gives you a new list with just those parts.

But remember, when you slice() lists with objects in them, changing the objects in the new list also changes them in the original. For completely separate copies, use other tricks like spreading (...) or turning the list into a string and back (JSON.parse()/stringify()).

This guide aimed to make slice() in JavaScript clear for you. We went through examples showing how to use it in real situations. Try playing around with it to see all the things it can do. And always slice carefully!

What does array slice do in JavaScript?

The slice() method in JavaScript takes certain parts of an array and makes a new array with them. It picks elements starting from one point and stops before another point, but it doesn't change the original array at all.

What is the purpose of array slicing?

Array slicing lets you take a smaller piece of a big array and work with it separately. It's like picking out a section of a book to read without having to carry the whole book. This is great for when you only need to focus on a part of the data.

How does array splice work in JavaScript?

Unlike slice(), the splice() method changes the original array by adding or taking away elements. You tell it where to start, how many elements to remove, and what new elements to add. So, it's a way to directly change what's in the array right where it is.

What is the difference between slice array and slice string?

  • When you use slice() on an array, you get a new array with just the parts you wanted. It doesn't mess with the original array.
  • When you use slice() on a string, you get a new string with just the part you wanted. Since strings can't be changed (they're immutable), this is just a way to get a piece of the string.

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more