r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

2

u/e13e7 Mar 19 '19

Not usually one lined, but short and useful nonetheless

const splitBy = (fn, arr) => arr.reduce(
  ([ l, r ], c) => fn(c)
    ? [ l.concat(c), r ]
    : [ l, r.concat(c) ],
  [[],[]]
)

// eg
const [ odd, even ] = splitBy(
  (x) => x % 2,
  [ 1, 2, 3, 4, 5 ]
)
→ More replies (1)