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


We are required to write a function for arrays Array.prototype.remove(). It accepts one argument; it is either a callback function or a possible element of the array. If it’s a function then the return value of that function should be considered as the possible element of the array and we have to find and delete that element from the array in place and the function should return true if the element was found and deleted otherwise it should return false.

Therefore, let’s write the code for this function −

Example

const arr = [12, 45, 78, 54, 1, 89, 67];
const names = [{
   fName: 'Aashish',
   lName: 'Mehta'
}, {
      fName: 'Vivek',
      lName: 'Chaurasia'
}, {
      fName: 'Rahul',
      lName: 'Dev'
}];
const remove = function(val){
   let index;
   if(typeof val === 'function'){
      index = this.findIndex(val);
   }else{
      index = this.indexOf(val);
   };
   if(index === -1){
      return false;
   };
   return !!this.splice(index, 1)[0];
};
Array.prototype.remove = remove;
console.log(arr.remove(54));
console.log(arr);
console.log(names.remove((el) => el.fName === 'Vivek'));
console.log(names);

Output

The output in the console will be −

true
[ 12, 45, 78, 1, 89, 67 ]
true
[
   { fName: 'Aashish', lName: 'Mehta' },
   { fName: 'Rahul', lName: 'Dev' }
]

Updated on: 25-Aug-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements