flattenOnce

flattenOnce

  • (anArray: array) => array
  1. Flatten an array one level deep.

    flattenOnce(['a', ['b', ['c']]]) // is ['a', 'b', ['c']]
    flattenOnce(['a', ['b', ['c']]]) // is ['a', 'b', ['c']]
    
    flattenOnce(['a', ['b', ['c']]]) // is ['a', 'b', ['c']]
    flattenOnce(['a', ['b', ['c']]]) // is ['a', 'b', ['c']]
    
  2. Sometimes we have nested arrays and only want to flatten one level deep. Below, a doctor is examining the medical history of relatives and wants to limit her search to the patient's cousins. Let's flatten the tree one level to do this.

    const secondCousins = ['amy', 'kim']
    const cousins = ['matt', 'jason']
    const siblings = ['phil', 'mary', 'sarah']
    const extendedFamily = [...siblings, [...cousins, [...secondCousins]]]
    
    const isString = element => typeof element === 'string'
    const siblingsAndCousins = flattenOnce(extendedFamily).filter(isString)
    console.log(siblingsAndCousins)
    // is [
    //   phil,
    //   mary,
    //   sarah,
    //   matt,
    //   jason,
    // ]
    const secondCousins = ['amy', 'kim']
    const cousins = ['matt', 'jason']
    const siblings = ['phil', 'mary', 'sarah']
    
    type FamilyTree = (string | FamilyTree)[]
    const extendedFamily: FamilyTree = [
      ...siblings,
      [...cousins, [...secondCousins]],
    ]
    
    const isString = (node: string | FamilyTree) => typeof node === 'string'
    const siblingsAndCousins = flattenOnce(extendedFamily).filter(isString)
    console.log(siblingsAndCousins)
    // is [
    //   phil,
    //   mary,
    //   sarah,
    //   matt,
    //   jason,
    // ]
    
    const secondCousins = ['amy', 'kim']
    const cousins = ['matt', 'jason']
    const siblings = ['phil', 'mary', 'sarah']
    const extendedFamily = [
      ...siblings,
      [...cousins, [...secondCousins]],
    ]
    
    const isString = element =>
      typeof element === 'string'
    const siblingsAndCousins = flattenOnce(
      extendedFamily
    ).filter(isString)
    console.log(siblingsAndCousins)
    // is [
    //   phil,
    //   mary,
    //   sarah,
    //   matt,
    //   jason,
    // ]
    const secondCousins = ['amy', 'kim']
    const cousins = ['matt', 'jason']
    const siblings = ['phil', 'mary', 'sarah']
    
    type FamilyTree = (string | FamilyTree)[]
    const extendedFamily: FamilyTree = [
      ...siblings,
      [...cousins, [...secondCousins]],
    ]
    
    const isString = (node: string | FamilyTree) =>
      typeof node === 'string'
    const siblingsAndCousins = flattenOnce(
      extendedFamily
    ).filter(isString)
    console.log(siblingsAndCousins)
    // is [
    //   phil,
    //   mary,
    //   sarah,
    //   matt,
    //   jason,
    // ]