Dividing an array by filter function

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

    What about this?

    [1,4,3,5,3,2].reduce( (s, x) => { s[ x > 3 ].push(x); return s;} , {true: [], false:[]} )
    

    Probably this is more efficient then the spread operator

    Or a bit shorter, but uglier

    [1,4,3,5,3,2].reduce( (s, x) => s[ x > 3 ].push(x)?s:s , {true: [], false:[]} )
    
    

提交回复
热议问题