Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove value from associative array [duplicate]

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?

like image 314
Niraj Chauhan Avatar asked Jan 27 '13 15:01

Niraj Chauhan


People also ask

How do you remove a repeating value from an array?

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.

Can you delete elements from an associative 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.

Does In_array work for associative 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.

How do you remove duplicates from an array in place in PHP?

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.


2 Answers

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.

like image 175
David G Avatar answered Sep 18 '22 07:09

David G


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); } 
like image 35
techfoobar Avatar answered Sep 21 '22 07:09

techfoobar