1

I have an array with the following structure :

var y = [{id:12,count:10}, {id:23,count:89}, {id:21,count:100},]

How can I remove element with id:23 ?

I am not willing to use to create a prototype method on the array Array.prototype.remove

Any pointers appreciated

Thanks

1

3 Answers 3

5

ES5 code:

y = y.filter(function( obj ) {
    return obj.id !== 23;
});

ES5 is widely supported by all major browsers. Still, you might want to include on of the several Shims to backup old'ish browsers

Sign up to request clarification or add additional context in comments.

Comments

3
for (i in y) {
    if (y[i].id == 23) {
       y.splice(i, 1);
       break;
    }
}

7 Comments

if it's possible for there to be two elements with the matching id then this could fail (if they dups are in sequence), and if there is only one then there should be a break inside the if block.
its pretty bad to use a for in to iterate over an array. You might end up iterating methods/functions or propertys on the Array aswell. Better use a standard for loop.
In all major browsers variable i will never have property name of Array object.
@DenisErmolin: on what grounds are you making that claim?
Very good question. That is just wrong.. of course ANY browser will list the object properties aswell. Easy example: var foo = [1,2,3]; foo.IAMBOSSBITCH = true; loop over that...
|
0

Denis Ermolin's answer is an option, though a few problems might occur, here's what I suggest:

for(var i=0;i<y.length;i++)
{
    if (y[i].hasOwnProperty('id') && y[i].id === 23)
    {
        delete(y[i]);
        break;
    }
}

When using arrays, it's always better to avoid the for - in loop, as this will loop through the Array.prototype, so i might suddenly contain length, not an index number.

When you're dealing with objects, the for in loop is a great thing, but again: it loops through the prototypes, that's why you're better off using the hasOwnProperty method.

The rest is pretty strait forward, I think... good luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.