Dividing an array by filter function

后端 未结 12 1059
抹茶落季
抹茶落季 2020-12-01 11:24

I have a Javascript array that I would like to split into two based on whether a function called on each element returns true or false. Essentially

12条回答
  •  鱼传尺愫
    2020-12-01 12:14

    This sounds very similar to Ruby's Enumerable#partition method.

    If the function can't have side-effects (i.e., it can't alter the original array), then there's no more efficient way to partition the array than iterating over each element and pushing the element to one of your two arrays.

    That being said, it's arguably more "elegant" to create a method on Array to perform this function. In this example, the filter function is executed in the context of the original array (i.e., this will be the original array), and it receives the element and the index of the element as arguments (similar to jQuery's each method):

    Array.prototype.partition = function (f){
      var matched = [],
          unmatched = [],
          i = 0,
          j = this.length;
    
      for (; i < j; i++){
        (f.call(this, this[i], i) ? matched : unmatched).push(this[i]);
      }
    
      return [matched, unmatched];
    };
    
    console.log([1, 2, 3, 4, 5].partition(function (n, i){
      return n % 2 == 0;
    }));
    
    //=> [ [ 2, 4 ], [ 1, 3, 5 ] ]
    

提交回复
热议问题