Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an element from an array specifying a value in Javascript

I have read this question:

Deleting array elements in JavaScript - delete vs splice

And it appears that both splice and delete require an index of the element in order to remove, so how can I easily find the index when I have the value?

For example if I have an array that looks like this:

["test1", "test2", "test3"]

and I want to remove test2. The process I am using right now, which I'm hoping isn't the correct way to do it, is using $.each checking the value of each element in the array, maintaining a counter through the process (used as the index reference) and if the value is equal to "test2", then I have my index (in form of the counter) and then use splice to remove it.

While the array grows larger, I would imagine this would be a slow process, but what alternatives do I have?

like image 496
Doug Molineux Avatar asked Aug 10 '11 17:08

Doug Molineux


People also ask

How do you remove an element from an array with 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.

How do I remove an item from an array?

Use splice() to remove arbitrary item The correct way to remove an item from an array is to use splice() . It takes an index and amount of items to delete starting from that index.

How do you remove an element from an array in another array?

For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.


2 Answers

You want to use the splice() function to remove the item, indexOf will find it in the array:

To Find a specific element in the Array: (to know which to remove)

var index = array.indexOf('test2'); 

Full Example:

var array = ['test1', 'test2', 'test3'];
var value_to_remove = 'test2';
array.splice(array.indexOf(value_to_remove), 1); 

Working Demo

like image 158
Rion Williams Avatar answered Oct 20 '22 14:10

Rion Williams


var array = ["test1", "test2", "test3"];
array.splice(array.indexOf("test2"), 1);

indexOf (source):
Returns the first index at which a given element can be found in the array, or -1 if it is not present.

like image 28
Shaz Avatar answered Oct 20 '22 12:10

Shaz