javascript - remove array element on condition

javascript

Solution

You could add your own method to `Array` that does something similar, if `filter` does not work for you.

Array.prototype.removeIf = function(callback) {
    var i = 0;
    while (i < this.length) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
        else {
            ++i;
        }
    }
};

To me, that's one of the coolest features of JavaScript. Ian pointed out a more efficient way to do the same thing. Considering that it's JavaScript, every bit helps:

Array.prototype.removeIf = function(callback) {
    var i = this.length;
    while (i--) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
    }
};

This avoids the need to even worry about the updating `length` or catching the next item, as you work your way left rather than right.

Problem

I was wondering how I'd go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery) Ex. ``` ar = [ 1, 2, 3, 4 ]; ar.removeIf( function(item, idx) { return item > 3; }); ``` The above would go through each item in the array and remove all those that `return true` for the condition (in the example, item > 3). I'm just starting out in javascript and was wondering if anyone knew of a short efficient way to get this done. --update-- It would also be great if the condition could work on object properties as well. Ex. ``` ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ]; ar.removeIf( function(item, idx) { return item.str == "c"; }); ``` Where the item would be removed if `item.str == "c"` --update2-- It would be nice if index conditions could work as well. Ex. ``` ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ]; ar.removeIf( function(item, idx) { return idx == 2; }); ```

Original source