Dividing an array by filter function

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

    With ES6 you can make use of the spread syntax with reduce:

    function partition(array, isValid) {
      return array.reduce(([pass, fail], elem) => {
        return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
      }, [[], []]);
    }
    
    const [pass, fail] = partition(myArray, (e) => e > 5);
    

    Or on a single line:

    const [pass, fail] = a.reduce(([p, f], e) => (e > 5 ? [[...p, e], f] : [p, [...f, e]]), [[], []]);
    

提交回复
热议问题