How can I remove a specific item from an array JavaScript?


Let’s say, we have an array of numbers and we added elements to it. You need to devise a simple way to remove a specific element from an array.

The following is what we are looking for −

array.remove(number);

We have to use core JavaScript. Frameworks are not allowed.

Example

The code for this will be −

const arr = [2, 5, 9, 1, 5, 8, 5];
const removeInstances = function(el){
   const { length } = this;
   for(let i = 0; i < this.length; ){
      if(el !== this[i]){
         i++;
         continue;
      }
      else{
         this.splice(i, 1);
      };
   };
   // if any item is removed return true, false otherwise
   if(this.length !== length){
      return true;
   };
   return false;
};
Array.prototype.removeInstances = removeInstances;
console.log(arr.removeInstances(5));
console.log(arr);

Output

And the output in the console will be −

true
[ 2, 9, 1, 8 ]

Updated on: 24-Nov-2020

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements