1

i am trying to remove some items in an json object list, the ones that have a specific group. My JSON looks like this.

var events = [
        {"id":"19","name":"sports","group":"1"},
        {"id":"20","name":"school","group":"2"},
        {"id":"21","name":"fun","group":"1"}
    ]

I tried this

for(var i in events)
    if(events[i].group == deleted_group)
        events.splice(i, 1);

But the problem of this, is that if i have to remove more items, it bugs out. Is there another easy way to to this ? I am open for sugestion even using underscore.js .

Thank you in advance, Daniel!

3 Answers 3

1

Try this

var events = [
    {"id":"19","name":"sports","group":"1"},
    {"id":"20","name":"school","group":"2"},
    {"id":"21","name":"fun","group":"1"}
]

console.log(_.reject(events, function(event){ return event.group == '1'; }));
Sign up to request clarification or add additional context in comments.

2 Comments

this works great, thank you very much and also to everyone on this topic
@PacuraruDaniel underscore solution is good indeed - I missed that you're using underscore in my answer. My answer is for people who don't want to use underscore and are interested in pure JS solution.
0

When you're using the "splice" function to remove elements from the array inside a for loop, you need to shift your current index back when removing an item since the array is reindexed.

Also take a look at the array functions like "filter" for a more convenient way, read more on MDN.

1 Comment

Filter seems to be the right answer to the question, however, IE<9 doesn't support Array.prototype.filter.
0

You can use delete operator to delete objects (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete):

delete events[0]

The problem with delete is, that in your array, as a value of events[0] it will leave undefined.

So another way (the way I would choose for your simple example) is to just rewrite the array:

var temp_events = [];
for(var i in events)
    if(events[i].group != deleted_group)
        temp_events[temp_events.length] = events[i];
events = temp_events;

Executing splice in a for loop has complexity n^2 (where n is number of elements). Rewriting has linear complexity.

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.