Pregunta

I would like to delete specific positions in an array and also reduce the length of the array such that it doesn't contain an undefined position after the delete. I'm also iterating over the array.

I can imagine a brute-force solution which would iterate twice over the array, but I just thought I'd check and see if there's something easier out there.

Here's what I've got:

_.each(foo._events, function (eventGroup) {

    var keys = _.keys(eventGroup);

    _.each(keys, function (key) {
        if (eventGroup[key].ctx.isClosed) {
            delete eventGroup[key];
            console.log("Deleting closed");
        }
    });
});

This leaves an undefined element in the slot, though.

I was exploring some of the options here: How do I remove a particular element from an array in JavaScript? but I suspect modifying the array's length while iterating over it might result in odd behavior? But maybe it's fine since I'm accessing by key -- even though the keys appear to be "0", "1", "2".

¿Fue útil?

Solución

I'm not sure I understood completely, but maybe filter is what you're looking for?

foo._events = _.filter(foo._events, function (eventGroup) {
    return _.every(_.values(eventGroup), function(v) {
         return !v.ctx.isClosed
    })
})

Otros consejos

Rather than iterating over the array twice, have you thought about sliding the elements down in one loop? I.e., once you find the index of the element to delete, assign the value at that index i to the value at index i + 1, so on and so forth. You're right, changing the size of the array while iterating is dangerous, and in stricter languages is not even allowed. Once you're done reassigning the elements within the loop, you can change the size to N - 1.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top