Removing Elements From An Array

codethepotato

codethepotato

Posted on June 25, 2023

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

💖 💪 🙅 🚩
codethepotato
codethepotato

Posted on June 25, 2023

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

Sign up to receive the latest update from our blog.

Related

What's a function in JavaScript?
beginners What's a function in JavaScript?

July 22, 2023

Removing Elements From An Array
javascript Removing Elements From An Array

June 25, 2023

How to do bit manipulation in JavaScript
javascript How to do bit manipulation in JavaScript

February 11, 2021