Skip to main content

Archive

Show more

How to remove a specific item from an array in javascript

how-to-remove-specific-item-from-array-in-javascript


Question: How to remove a specific item from an array in javascript

Answer:

Here are two possibilities, the first is to remove only one item from the array, other is to remove all elements of the same value in the array.But when we remove multiple items from an array, a loop is required. while to remove one item in loop requires. We will discuss both concepts in this article.


Removing one item from array.

var myArray = ["green","yellow","black","red","black","orange","white","orange"];

function removeItem(array, value){
  let index = array.indexOf(value);

  if (index > -1) {
   array.splice(index, 1);
  }
}

removeItem(myArray, 'red');

console.log(myArray);

Output:

["green", "yellow", "red", "orange", "white", "orange"]


Removing all the same value items from the array ( removing one or more items).

var myArray = ["green","yellow","black","red","black","orange","white","orange"];

function removeItem(array, value) {
 var index = null;

 while ((index = array.indexOf(value)) !== -1)
   array.splice(index, 1);
  
};

removeItem(myArray, 'orange');

console.log(myArray);

Output:

["green", "yellow", "black", "red", "black", "white"]


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments