Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery remove element from array

This should be fun to solve :)

In a text field I have the value Apple,Peach,Banana.

Using Jquery I created an array from that CSV.

In HTML I have a list of the fruits with a "remove" option next to each one. When I click "remove" I want to remove the corresponding fruit from the list and the text field.

I'm missing one function that will remove fruits from the array. What function should I use?

http://jsfiddle.net/BXWqK/19/

like image 879
CyberJunkie Avatar asked Jun 04 '11 02:06

CyberJunkie


People also ask

How do I remove a specific element from an array?

Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.

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

Remove Array elements by using pop() method: This method is used to remove the last element of the array and returns the removed element. This function decreases the length of the array by 1. Example 1: javascript.

How do you remove an element from a string array?

We can use an ArrayList to perform this operation. To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.

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


1 Answers

The accepted solution is correct, but it doesn't mention that you shouldn't use indexOf to get the fruit_index to remove, because IndexOf not Supported in IE8 Browser

You should use:

fruits_array.splice($.inArray('Peach', fruits_array), 1);
like image 148
Doug Avatar answered Sep 19 '22 15:09

Doug