EN
JavaScript - remove value from associative array
1
answers
0
points
I have an array from which I want to remove a value.
var associativeArray = { items: ['item1', 'item2'] };
Now I just want to remove item2
. How can I do that? I tried using delete
operator but it didn't work.
1 answer
0
points
Use object property accessors (since associative arrays are objects) combined with splice()
method.
Practical examples
1. When you know the index of the element you want to remove:
// ONLINE-RUNNER:browser;
var associativeArray = { items: ['item1', 'item2'] };
associativeArray.items.splice(1, 1);
console.log(JSON.stringify(associativeArray)); // { items: [ 'item1' ] }
2. When you don't know the index of the element you want to remove:
// ONLINE-RUNNER:browser;
function removeElement(object, property, element) {
var index = object[property].indexOf(element);
if (index === -1) return;
return object[property].splice(index, 1);
}
// Usage example:
var associativeArray = { items: ['item1', 'item2'] };
removeElement(associativeArray, 'items', 'item2'); // removes 'item2' from 'items' inside associativeArray object
console.log(JSON.stringify(associativeArray)); // { items: [ 'item1' ] }
Note:
The solution above is a simple reusable function that will work for any associative arrays (for non-nested objects).
See also
References
0 comments
Add comment