This post will discuss how to remove an element from an array based on its index in JavaScript.

To remove an element from an array based on its index in JavaScript, we need to delete the element at that position and shift the other elements to the left. Here are some of the ways that we can use:

1. Using splice() function

The splice() function can change the content of an array by removing existing elements. We can use it to remove the element at a given index by passing the index and a delete count of one to the function. The splice() function returns a new array containing the removed element. For example, if we have an array [1, 2, 3, 4, 5] and we want to remove the element at index 2, we can do:

Download  Run Code

2. Using slice() function

The slice() function returns a shallow copy of a portion of an array into a new array object. We can use it to create a new array without the element at a given index by passing a start index of zero and an end index of the given index, and then concatenating it with another slice that starts from the given index plus one. The concatenation can be done using the concat() function or the spread operator (…). For example, if we have an array [1, 2, 3, 4, 5] and we want to create a new array without the element at index 2, we can do:

Download  Run Code

3. Using filter() function

The filter() function creates a new array with all elements that pass a predicate implemented by the callback function. We can use them to create a copy of the original array without the element at a given index by using a function that returns true for all elements except the one at the given index. For example, if we have an array [1, 2, 3, 4, 5] and we want to create a new array without the element at index 2, we can do:

Download  Run Code

4. Using a custom function

We can also write our own function that takes an array and an index as arguments and returns a new array with the element at that index removed. We can use a for loop or a map function to iterate over the elements of the original array and copy only those that are not at the given index to a new array. For example, we can use something like this:

Download  Run Code

However, this will also remove any existing undefined values from the original array. To handle it, we can return any custom value from the callback of the map() function. That’s all about removing an element from an array based on its index in JavaScript.