Remove/Delete an specific item from array
As JS programmer, We have observed this problem several time, where we need to remove specific item from array.
Lets take an example
let numArray = [58,38,3,2,12,56,7];
We want to remove number 2 from numArray, There are multiple way to achieve this
This function will return new array with elements which passed by callback function
This function take 2 argument
- callbackFunction=>This will be called to each element and added to new array if it returns true.
- this
const numberTobeRemoved = 2;
let numArray = [58,38,3,2,12,56,7];
numArray = numArray.filter(num => num != numberTobeRemoved);
console.log(numArray);
Splice is used to remove/update the content of specific position in array
Approach 1
- Find the index of element using indexOf
- splice the array.
const numberTobeRemoved = 2;
let numArray = [58, 38, 3, 2, 12, 56, 7];
let rIndex = numArray.indexOf(numberTobeRemoved);
if (rIndex != -1)
numArray.splice(rIndex, 1);
console.log(numArray);
I observed one issue with this approach, It will not remove all elements because of indexOf will return first index of given elements.
Approach 2
Loop to find the index of element using indexOf in loop and splice the array.
const numberTobeRemoved = 2;
let numArray = [58, 38, 3, 2, 12, 56, 7, 2];
let rIndex = -1;
do {
rIndex = numArray.indexOf(numberTobeRemoved);
if (rIndex != -1)
numArray.splice(rIndex, 1);
} while (rIndex != -1)
console.log(numArray);
Use this code wherever you need to use it.