Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array search and remove string?

I have:

var array = new Array(); array.push("A"); array.push("B"); array.push("C"); 

I want to be able to do something like:

array.remove("B");

but there is no remove function. How do I accomplish this?

like image 953
Rolando Avatar asked Mar 20 '12 18:03

Rolando


People also ask

How do I remove a particular element from an array in JavaScript?

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.

How do you delete a matching element from an array?

The splice() function adds or removes an item from an array using the index. To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.


1 Answers

I'm actually updating this thread with a more recent 1-line solution:

let arr = ['A', 'B', 'C']; arr = arr.filter(e => e !== 'B'); // will return ['A', 'C'] 

The idea is basically to filter the array by selecting all elements different to the element you want to remove.

Note: will remove all occurrences.

EDIT:

If you want to remove only the first occurence:

t = ['A', 'B', 'C', 'B']; t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B'] 
like image 98
Tyrannas Avatar answered Sep 23 '22 17:09

Tyrannas