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/
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With