JavaScript Array Splice() Method: Adding and Removing Elements Made Easy.

JavaScript Array Splice() Method: Adding and Removing Elements Made Easy.

The other day I was working with an array and I wanted to remove an element from the array based on an id.

To remove any vagueness I was working on a shopping cart and I needed to make the remove item button functional.

Here is a snippet of the code for the remove item button. I am using redux toolkit for this project. If you are unfamiliar with the famous state management library ignore the verbose code.

removeSelectedFood : (state, action) =>{

            const { id } = action.payload

            const index = state.value.findIndex(food =>food.id === id)

            if(index !== -1){

                state.value.splice(index, 1)
            }
        }

Before coming up with this solution I was thinking to myself how can I achieve this I had only one thing on my mind I wanted to achieve this with maybe just two or three lines of code.

I did not want to use a filter method as it would require more lines of code and I wanted to avoid that by all means necessary.

Oops Did I lose you? I was lost talking about this solution I can up with. Let’s backtrack………….

What is an array?

You know what a list is right? A list is when you write down a bunch of things you want to remember.

An array in JavaScript is like a special kind of list. It's also a bunch of things you want to remember, but it's special because you can do cool things with it. You can add things to the list, take things away from the list, and even change things that are already on the list.

So if you have a bunch of things you want to remember and you want to be able to do cool things with them, you can use an array in JavaScript. Cool, huh? If you think arrays are cool say so in the comment section.

To create an array in JavaScript, use the following syntax:

const arrayName = [element1, element2, element3, ...]

Where arrayName is the name you give to your array, and element1, and element2, are the elements you want to include in your array. You can include any type of data in an array, including strings, numbers, and even objects.

Just like your list, you have various ways of removing or editing the contents of your list. You can use an eraser or a white-out or you can get rid of the list completely. Also in JavaScript, there are many ways to edit the contents of your array and they are called methods.

In this article, I am going to talk about one specific array method called the splice method.

The splice method is used to mutate the contents of an array. The splice method takes two or three arguments depending on the kind of operation you wish to carry out.

The array splice method can either insert elements into an array or remove elements from an array. How is that for an MVP method?

The syntax for using the splice method in JavaScript is as follows:

array.splice(start, deleteCount, item1, item2, ...)
  • start The index at which to start changing the array.

  • deleteCount: An integer indicating the number of old array elements to remove. If deleteCount: Number of items to be deleted.

  • item1, item2, ...: The elements to add to the array.

Let's explore what the splice method can do. shall we?

How to remove elements from an array

This was what I wanted to achieve when working on that reducer I was working. (See the code snippet at the very top).

Just like your grocery list or your to-do list. You might want to mark a task as done or remove an item from your grocery list completely if you do not need it. The prices of groceries are high right now.

The splice method can help you do all of the above. So let’s rip this thing apart. Look at the code snippet below.

const citrusFruits = ['orange', 'lemon', 'lime', 'grapefruit'];
citrusFruits.splice(1, 2);
console.log(citrusFruits); // Output: ['orange', 'grapefruit']

In the code snippet, we begin at index 1 (which is the second item in the array. You do know how to count items in an array right?) we begin at index 1 and if you look at the syntax we also want to remove 2 elements from index position 1 and we are finally left with “orange” and “grapefruit”.

Breaking the syntax even further. The first parameter which is number 1 is the index where the operation is started. The second parameter 2 is how many items are to be removed from that index in the array.

How to add elements to an array

You are about to go get groceries and you remember I’ve run out of eggs. What do you? Yes, you guessed right you add eggs to your grocery list. The same thing can be done to an array, elements can be added.

Once more let’s rip this thing apart. Hope you do not get tired of ripping things apart.

const citrusFruits = ['orange', 'lemon', 'lime', 'grapefruit'];
citrusFruits.splice(citrusFruits.length, 0, 'tangerine', 'mandarin');
console.log(citrusFruits); // Output: ['orange', 'lemon', 'lime', 'grapefruit', 'tangerine', 'mandarin']

The code snippet above is an example of how you can add elements to an array using the splice method.

First, we look for the length of the array which is the index we wish to add the elements to the array.

Second, we do not specify how many items to be added to that array and finally, the elements to be added to the array which are “tangerine” and “mandarin”.

Conclusion

The splice method is a really handy array method. With some practice, you can begin to alter the elements in an array like a pro. I know you like the sound of that.