0

I have array like this

var curChanges = [
                   {id:1, isChecked:true},
                   {id:2, isChecked:false},
                   {id:3, isChecked:true}
                 ];

Now, if i want to remove second array i.e {id:2, isChecked:false} dynamically, How do i do? Here id is unique.

Thanks in advance.

Chandu
  • 962
  • 2
  • 16
  • 33

2 Answers2

2

Firstly, you have a syntax error. Object property values are set with :, not with =:

var curChanges = [
    {
        id: 1,
        isChecked: true
    },
    // etc...
];

Assuming the order of elements in the array is not fixed, the easiest way to achieve what you're trying to do will be to use the ES5 Array.prototype.filter method:

curChanges.filter(function (elem) {
    return elem.id !== 2;
});

If you return true from the filter function, the element will stay in the array. If you return false, it will be removed.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    Just to clarify, you would have to do `curChanges = curChanges.filter(function` because it returns a new array and does not modify the existing one. – Jeff Shaver Mar 28 '13 at 11:22
  • +1 because correct. An exmaple function ´removeElementWithId´ would be nice, but all in all sound. :) – winner_joiner Mar 28 '13 at 11:22
0

first off, invalid array. Should be : not =

so it becomes:

var curChanges = [ {id:1, isChecked:true}, {id:2, isChecked:false}, {id:3, isChecked:true}];

Use a filter to remove based on id:

curChanges.filter(function(i) { return i.id!=2;})

Or to directly remove the second element :

curChanges.splice(1,1);
loxxy
  • 12,990
  • 2
  • 25
  • 56