Dividing an array by filter function

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

    I ended up doing this because it's easy to understand (and fully typed with typescript).

    const partition = (array: T[], isValid: (element: T) => boolean): [T[], T[]] => {
      const pass: T[] = []
      const fail: T[] = []
      array.forEach(element => {
        if (isValid(element)) {
          pass.push(element)
        } else {
          fail.push(element)
        }
      })
      return [pass, fail]
    }
    
    // usage
    const [pass, fail] = partition([1, 2, 3, 4, 5], (element: number) => element > 3)
    

提交回复
热议问题