DEV Community

Cover image for How to Easily Add and Remove Any Elements from a JavaScript Array
Amit Mehta
Amit Mehta

Posted on • Originally published at indepthjavascript.dev

How to Easily Add and Remove Any Elements from a JavaScript Array

In this post I want to discuss a super useful way to add and remove elements from ANY index in a javaScript array.

You're probably familiar with push, pop, unshift, and shift. They come in handy for sure, if you want to add and remove elements from the beginning or the end of the array.

However, there are a TON of different scenarios where you will need to insert and remove array elements from any position.

This is worth memorizing cold!

Let's start with an array of animals...

const animals = ['😺' , '🙉' , '🧞','🦊', '🦁', '🐯', '🐵'];
Enter fullscreen mode Exit fullscreen mode

Wait! There's a genie in the list at index 2. Not sure how that snuck in there 😂. Let's go ahead and remove that array element.

const genieIndex = 2;

animals.splice(genieIndex,1);

console.log(animals);
// => ['😺' , '🙉' ,'🦊', '🦁', '🐯', '🐵'];
Enter fullscreen mode Exit fullscreen mode

splice(index,1) removes the array element located at index. Very simple.

Now 🐶 is feeling left out, so let's add him into the array at index equal to 2.

Again, we can use the splice array method.

const index = 2;

animals.splice(index, 0,'🐶');

console.log(animals);
// => ['😺' , '🙉' ,'🐶','🦊', '🦁', '🐯', '🐵'];
Enter fullscreen mode Exit fullscreen mode

splice(index, 0,'🐶') inserts the dog emoji at position index.

Now there are definitely more sophisticated array manipulations you can do with splice. However, start by memorizing how to add and remove array elements with splice. You'll thank me later!

If you enjoyed this article please check out my blog
Indepth JavaScript for more illuminating
content.

Latest comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Good guide for the JavaScript splice method.