Languages

JavaScript - remove value from associative array

0 points
Asked by:
Wayne
475

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
Answered by:
Wayne
475

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

  1. JavaScript - remove object from associative array

  2. JavaScript - remove array element based on object property

References

  1. Property accessors - JavaScript | MDN
  2. Array.prototype.slice() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join