Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to remove array element by value

I have an array like this

arr = ["orange","red","black","white"] 

I want to augment the array object defining a deleteElem() method which acts like this:

arr2 = arr.deleteElem("red"); // ["orange","black","white"] (with no hole) 

What is the best way to accomplish this task using just the value parameter (no index)?

like image 686
antonjs Avatar asked Sep 05 '11 16:09

antonjs


People also ask

How do I remove an element from an array by value?

We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.

How can I remove a specific item from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


1 Answers

Here's how it's done:

var arr = ["orange","red","black","white"]; var index = arr.indexOf("red"); if (index >= 0) {   arr.splice( index, 1 ); } 

This code will remove 1 occurency of "red" in your Array.

like image 77
Maurício Linhares Avatar answered Sep 19 '22 20:09

Maurício Linhares