JavaScript

How to remove an element from an array with JavaScript

October 30, 2021

How to remove an element from an array with JavaScript

In this article we will learn, in a simple way, how to remove an element from an array using a native method of the JavaScript language.

remove an element from array cover

What’s up, programmer, are you okay? Let’s learn something new!

Watch this content:

Sometimes we need to delete an element from the array, so for this case we can resort to native JavaScript functions

There are many of them for arrays! 😀

To remove elements, we have 3 widely used ways, they are:

  • pop;
  • shift;
  • splice;

Remove element with pop

The pop method allows us to remove an element at the end of the array

Let’s see in practice:

let nums = [10,20,30,40,50];
nums.pop();
console.log(nums); // [10, 20, 30, 40]

Note: we can even assign the pop to a variable, and its return will be the removed element, which can be used for another purpose

Remove element from array with shift

The shift method removes the first element from the array.

Check out this code:

let nums = [10,20,30,40,50];
nums.shift();
console.log(nums); // [20,30,40,50]

Note: the shift method also returns the removed element!

Removing and element with splice

And so far we haven’t discussed about how to remove a specific element in the array

For this we will have to use the splice method, then we will remove the element by the index

Or even more than one element

Let’s see the splice in action:

let pessoas = ['Matheus', 'João', 'Pedro', 'Marcos'];
pessoas.splice(2, 1);
console.log(pessoas); // ['Matheus', 'João', 'Marcos']

In the splice method we write two arguments, the first one is the index of the element to be removed

The second one is the number of elements that must be removed, that is, in the example as we stated 1, it only removed the ‘Pedro’ which was the index 2. Did you understand that? 🙂

Conclusion

In this article we learned how to remove elements from an array in three ways

pop: removes an element from the end of the array;

shift: removes an element from the beginning of the array;

splice: remove elements by index;

And that’s it for today, see you on the next post! 🙂

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x