Dividing an array by filter function

后端 未结 12 1069
抹茶落季
抹茶落季 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条回答
  •  旧时难觅i
    2020-12-01 12:05

    I came up with this little guy. It uses for each and all that like you described, but it looks clean and succinct in my opinion.

    //Partition function
    function partition(array, filter) {
      let pass = [], fail = [];
      array.forEach((e, idx, arr) => (filter(e, idx, arr) ? pass : fail).push(e));
      return [pass, fail];
    }
    
    //Run it with some dummy data and filter
    const [lessThan5, greaterThanEqual5] = partition([0,1,4,3,5,7,9,2,4,6,8,9,0,1,2,4,6], e => e < 5);
    
    //Output
    console.log(lessThan5);
    console.log(greaterThanEqual5);

提交回复
热议问题