Remove/Delete an specific item from array

Ashish Kasama
2 min readFeb 1, 2022

--

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

Use Array.prototype.filter()

This function will return new array with elements which passed by callback function

This function take 2 argument

  1. callbackFunction=>This will be called to each element and added to new array if it returns true.
  2. this

const numberTobeRemoved = 2;
let numArray = [58,38,3,2,12,56,7];
numArray = numArray.filter(num => num != numberTobeRemoved);
console.log(numArray);

use Array.prototype.splice()

Splice is used to remove/update the content of specific position in array

Approach 1

  1. Find the index of element using indexOf
  2. 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.

--

--

Ashish Kasama
Ashish Kasama

Written by Ashish Kasama

Founder and CTO, I am responsible for implementing client thoughts into digital world, bring latest technology in day to day work

No responses yet