Possible Duplicate:
Remove specific element from a javascript array?
I am having an array, from which I want to remove a value.
Consider this as an array
[ 'utils': [ 'util1', 'util2' ] ]
Now I just want to remove util2
. How can I do that, I tried using delete
but it didn't work.
Can anyone help me?
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function. The following example shows how to delete an element from an associative array and numeric array.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.
Use the splice
method:
var object = { 'utils': [ 'util1', 'util2' ] } object.utils.splice(1, 1);
If you don't know the actual position of the array element, you'd need to iterate over the array and splice the element from there. Try the following method:
for (var i = object.utils.length; i--;) { var index = object.utils.indexOf('util2'); if (index === -1) break; if (i === index) { object.utils.splice(i, 1); break; } }
Update: techfoobar's answer seems to be more idiomatic than mine. Consider using his instead.
You can use Array.splice()
in combo with Array.indexOf()
to get the desired behavior without having to loop through the array:
var toDelete = object.utils.indexOf('util1'); if(toDelete != -1) { object.utils.splice(toDelete, 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