DEV Community

codethepotato
codethepotato

Posted on

Removing Elements From An Array

There are multiple ways an element can be removed from an array. We're going to discuss how to destructively and non destructively remove elements. It is crucial to think of how the code should run.

Destructively

There are two ways that elements can be added to an array with a destructive method. The reason they are called Destructive is because when used in a function they will change the original array with the passed in information.

.shift() removes the first element in an array

.pop() removes the last element in an array

The two methods are similar in these ways:

  1. They do not take any arguments
  2. They remove a single element
  3. They return the element that is removed

Nondestructively

This method works similar as the spread operator(...) if we don't add any arguments it will return a copy of the original array with all elements intact. Then removes an element without mutating the original array.

.slice()

We are able to add one-two arguments:

  1. First, is the index where the slice should begin
  2. Second, is the index where the slice should end
const snacks = ['Chips', 'Pretzels', 'M&Ms', 'Fruit', 'Veggies'];
const healthy = snacks.slice(3, 4);
Enter fullscreen mode Exit fullscreen mode

In the example above we are creating a new variable and assigning pieces of the original array without mutating the original array.

Some great resources are linked below.

W3Schools
Mozilla
React

Top comments (2)

Collapse
 
h4ywyre profile image
Carlos

So when you use the .slice method in the example code. 'Fruit' and 'Veggies" will be taken out of the array correct?

Collapse
 
codethepotato profile image
codethepotato

They will be made into a new array under 'healthy' all while leaving the original 'snacks' array together. Where in .splice() it would destructively take them out of the array, and they would no longer be in 'snacks', just 'healthy'.
Hope that made sense :) !