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); |
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