Dividing an array by filter function

后端 未结 12 942
抹茶落季
抹茶落季 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

    You can use reduce for it:

    function partition(array, callback){
      return array.reduce(function(result, element, i) {
        callback(element, i, array) 
          ? result[0].push(element) 
          : result[1].push(element);
    
            return result;
          }, [[],[]]
        );
     };
    

    Update. Using ES6 syntax you also can do that using recursion:

    function partition([current, ...tail], f, [left, right] = [[], []]) {
        if(current === undefined) {
            return [left, right];
        }
        if(f(current)) {
            return partition(tail, f, [[...left, current], right]);
        }
        return partition(tail, f, [left, [...right, current]]);
    }
    

提交回复
热议问题