Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove from array without using index number [duplicate]

Tags:

javascript

Possible Duplicate:
Remove item from array by value | JavaScript

How can I remove dog from the below array using Javascript. I do not want to use index if I can avoid it but rather the word dog instead.

["cat","dog","snake"]
like image 351
Jonathan Clark Avatar asked Dec 05 '22 18:12

Jonathan Clark


1 Answers

Given an array:

var arr = ["cat", "dog", "snake"];

Find its index using the indexOf function:

var idx = arr.indexOf("dog");

Remove the element from the array by splicing it:

if (idx != -1) arr.splice(idx, 1);

The resulting array will be ["cat", "snake"].

Note that if you did delete arr[idx]; instead of splicing it, arr would be ["cat", undefined, "snake"], which might not be what you want.

Source

like image 128
Claudiu Avatar answered Jan 21 '23 23:01

Claudiu