flattenToDepth
flattenToDepth
(depth: number) => (anArray: array) => array
Flatten an array N levels deep.
const flattenTwice = flattenToDepth(2) flattenTwice(['a', ['b', ['c', ['d']]]]) // is ['a', 'b', 'c', ['d']]
const flattenTwice = flattenToDepth(2) flattenTwice(['a', ['b', ['c', ['d']]]]) // is ['a', 'b', 'c', ['d']]
const flattenTwice = flattenToDepth(2) flattenTwice(['a', ['b', ['c', ['d']]]]) // is ['a', 'b', 'c', ['d']]
const flattenTwice = flattenToDepth(2) flattenTwice(['a', ['b', ['c', ['d']]]]) // is ['a', 'b', 'c', ['d']]
Sometimes we have nested arrays and only want to flatten to a specific depth. Below, Grace's corporation voted to give out bonuses due to their success. Only the highest-ranking employees deserve them, so let's find our top three tiers from our corporate tree.
const managers = ['meg', 'tom', 'ken'] const vicePresidents = ['mike', 'luke', 'emma'] const cSuite = ['sam', 'jen'] const ceo = 'grace' const corporateTiers = [ceo, [...cSuite, [...vicePresidents, [...managers]]]] const isString = element => typeof element === 'string' const flattenToVPs = flattenToDepth(2) const employeesWhoGetBonuses = flattenToVPs(corporateTiers).filter(isString) console.log(employeesWhoGetBonuses) // is [ // grace, // sam, // jen, // mike, // luke, // emma, // ]
const managers = ['meg', 'tom', 'ken'] const vicePresidents = ['mike', 'luke', 'emma'] const cSuite = ['sam', 'jen'] const ceo = 'grace' type CorporateTiers = (string | CorporateTiers)[] const corporateTiers: CorporateTiers = [ ceo, [...cSuite, [...vicePresidents, [...managers]]], ] const isString = (node: string | CorporateTiers) => typeof node === 'string' const flattenToVPs = flattenToDepth(2) const employeesWhoGetBonuses = flattenToVPs(corporateTiers).filter(isString) console.log(employeesWhoGetBonuses) // is [ // grace, // sam, // jen, // mike, // luke, // emma, // ]
const managers = ['meg', 'tom', 'ken'] const vicePresidents = ['mike', 'luke', 'emma'] const cSuite = ['sam', 'jen'] const ceo = 'grace' const corporateTiers = [ ceo, [...cSuite, [...vicePresidents, [...managers]]], ] const isString = element => typeof element === 'string' const flattenToVPs = flattenToDepth(2) const employeesWhoGetBonuses = flattenToVPs( corporateTiers ).filter(isString) console.log(employeesWhoGetBonuses) // is [ // grace, // sam, // jen, // mike, // luke, // emma, // ]
const managers = ['meg', 'tom', 'ken'] const vicePresidents = ['mike', 'luke', 'emma'] const cSuite = ['sam', 'jen'] const ceo = 'grace' type CorporateTiers = (string | CorporateTiers)[] const corporateTiers: CorporateTiers = [ ceo, [...cSuite, [...vicePresidents, [...managers]]], ] const isString = ( node: string | CorporateTiers ) => typeof node === 'string' const flattenToVPs = flattenToDepth(2) const employeesWhoGetBonuses = flattenToVPs( corporateTiers ).filter(isString) console.log(employeesWhoGetBonuses) // is [ // grace, // sam, // jen, // mike, // luke, // emma, // ]