4

Possible Duplicate:
JavaScript Array Delete Elements

So, in javascript, I have this set up:

global.menu = [{
   name: item1,
   price: price1,
   message: message1
},
{
   name: item2,
   price: price2,
   message: message2
},
{
   name: item3,
   price: price3,
   message: message3
}];

And my question is pretty simple, but how would I delete an object from this array?
To select an object, I'm using this command:

global.HandleMenu = function (b) {
    var c = menu.filter(function (d) {
        return d.name == b;
    });
    c.forEach(function (d) {
        Say(d.message);
    });
};

So yeah. Can I just add delete d;, or d.remove() inside the forEach function? Or am I missing something?

Community
  • 1
  • 1
Dalton Gore
  • 919
  • 2
  • 9
  • 21

2 Answers2

3

Assuming the name of the item you want to delete is in a variable called name, something like

for (var i = 0; i = global.menu.length - 1; i--) {
   var current = global.menu[i];
   if (current.name === name) global.menu.splice(i, 1);
}

should work. Note I'm not testing for nulls; but this is the general idea.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • This would work but how do I find the index of the object, with only the name of the object given? – Dalton Gore Jul 26 '12 at 00:08
  • this would work, but I like the above answer better, it's simpler and to the point. Thanks though! – Dalton Gore Jul 26 '12 at 00:12
  • @dalton, no problem. this is just an alternative. Note that my implementation modifies the actual array, filter creates a new array. – hvgotcodes Jul 26 '12 at 00:14
  • Yes, but it all works out if you're replacing the old array with the new array, doesn't it? – Dalton Gore Jul 26 '12 at 00:15
  • 1
    @DaltonGore: Not if there are other references to the original Array. They'll still be holding on to the old one. Probably safer to modify the original unless you can absolutely guarantee that no other code keeps a reference to `global.menu`. –  Jul 26 '12 at 00:24
  • am not i am, ah good point. excellent point in fact – hvgotcodes Jul 26 '12 at 00:25
2

use filter and re-assign

global.menu = global.menu.filter(function(a){ return a.item != "be delete" };
blueiur
  • 1,447
  • 1
  • 11
  • 17
  • This looks like it would delete the entire array, whereas I would only need to delete the object with selected name. – Dalton Gore Jul 26 '12 at 00:07
  • delete one item is equal to select other item without delete item. it's simple solution using list – blueiur Jul 26 '12 at 00:10
  • OHHHHHH. Derp. I just actually LOOKED at the code, thanks this is exactly what I'm looking for. Derp derp derp. – Dalton Gore Jul 26 '12 at 00:11
  • If there are any other references to the original `global.menu` Array, they'll remain unmodified. –  Jul 26 '12 at 00:22