javascript - remove array element on condition

后端 未结 7 764
北荒
北荒 2020-11-29 05:39

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)

相关标签:
7条回答
  • 2020-11-29 06:04

    I love these kinds of questions and just a different version from me too... :)

    Array.prototype.removeIf = function(expression) {
       var res = [];
        for(var idx=0; idx<this.length; idx++)
        {
          var currentItem = this[idx];
            if(!expression(currentItem))
            {
                res.push(currentItem);
            }
        }
        return res;
    }
    
    ar = [ 1, 2, 3, 4 ];
    var result = ar.removeIf(expCallBack);
    
    
    console.log(result);
    function expCallBack(item)
    {
        return item > 3;
    }
    
    0 讨论(0)
  • 2020-11-29 06:07

    simply write the following example if condition could work on object properties as well

    var ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
    var newArray = [];
    for (var i = 0, len = ar.length; i<len; i++) {
            if (ar[i].str == "b") 
            {newArray.push(ar[i]);};
     };
    console.log(newArray);
    

    See the example Live Example

    0 讨论(0)
  • 2020-11-29 06:11

    You can use Array filter method.

    The code would look like this:

    ar = [1, 2, 3, 4];
    ar = ar.filter(item => !(item > 3));
    console.log(ar) // [1, 2, 3]

    0 讨论(0)
  • 2020-11-29 06:15

    You can use Array.filter(), which does the opposite:

    ar.filter(function(item, idx) {
        return item <= 3;
    });
    
    0 讨论(0)
  • 2020-11-29 06:16

    You can use lodash.remove

    var array = [1, 2, 3, 4];
    var evens = _.remove(array, function(n) {
      return n % 2 == 0;
    });
    
    console.log(array);
    // => [1, 3]
    
    console.log(evens);
    // => [2, 4]
    
    0 讨论(0)
  • 2020-11-29 06:19

    Make it a one-liner with arrow function:

    ar = ar.filter(i => i > 3);
    
    0 讨论(0)
提交回复
热议问题