How to useindexOf() and slice() Methods in Javascript

This approach combines indexOf() to find the index of the item to be removed and slice() to create a new array by concatenating the parts of the original array before and after the specified index. It ensures that the original array remains unchanged.

Example: In this example, we are using indexOf() and slice().

Javascript




function removeItem(array, itemToRemove) {
    const index = array.indexOf(itemToRemove);
    console.log("Before:", array);
    if (index !== -1) {
        array = array.slice(0, index)
        .concat(array.slice(index + 1));
    }
    console.log("After:", array);
}
 
// Example usage:
const myArray3 = [1, 2, 3, 4, 5];
 // Removes the element 3
removeItem(myArray3, 3);


Output

Before: [ 1, 2, 3, 4, 5 ]
After: [ 1, 2, 4, 5 ]

How to Remove a Specific Item from an Array in JavaScript ?

To remove a specific item from an array, it means we have given an array with a number n and we have to remove the element present at index n. In this article, we are going to learn how to remove a specific item from an array in JavaScript.

Below are the approaches to remove a specific item from an array in JavaScript:

Table of Content

  • Using splice() Method
  • Using filter() Method
  • Using indexOf() and slice() Methods
  • Using filter() and !== Operator
  • Using indexOf() and concat() Methods

Similar Reads

Approach 1: Using splice() Method

JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements....

Approach 2: Using filter() Method

...

Approach 3: Using indexOf() and slice() Methods

JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array that satisfy a condition set by the argument method....

Approach 4: Using filter() and !== Operator

...

Approach 5: Using indexOf() and concat() Methods

This approach combines indexOf() to find the index of the item to be removed and slice() to create a new array by concatenating the parts of the original array before and after the specified index. It ensures that the original array remains unchanged....