I would like to do this with a single function.
I have a key=>value pair:
14=>1
I have an array containing many such pairs:
array(15=>2, 16=>7, 4=>9)
I want a function which will add the key=>value pair to the array in case it is not already there but it will remove it from the array if it is already there.
I would like to have a single function for this.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.
function updateArray($array, $findKey, $findValue) {
foreach($array as $key => $value) {
if ($key == $findKey AND $value == $findValue) {
unset($array[$key]);
return $array;
}
}
$array[$findKey] = $findValue;
return $array;
}
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