findKeyWithVal

findKeyWithVal

  • (value: any) => (collection: EntryCollection | string) => Key
  1. Find the first key or index of collection which has value.

    const findKeyOf2 = findKeyWithVal(2)
    const findKeyOfB = findKeyWithVal('b')
    
    findKeyOf2([1, 2, 3]) // is 1
    findKeyOf2([1, 2, 3, 2]) // is 1
    findKeyOf2([1, 3, 4]) // is undefined
    
    findKeyOf2({ a: 1, b: 2 }) // is 'b'
    findKeyOfB('ab') // is 1
    const findKeyOf2 = findKeyWithVal(2)
    const findKeyOfB = findKeyWithVal('b')
    
    findKeyOf2([1, 2, 3]) // is 1
    findKeyOf2([1, 2, 3, 2]) // is 1
    findKeyOf2([1, 3, 4]) // is undefined
    
    findKeyOf2({ a: 1, b: 2 }) // is 'b'
    findKeyOfB('ab') // is 1
    
    const findKeyOf2 = findKeyWithVal(2)
    const findKeyOfB = findKeyWithVal('b')
    
    findKeyOf2([1, 2, 3]) // is 1
    findKeyOf2([1, 2, 3, 2]) // is 1
    findKeyOf2([1, 3, 4]) // is undefined
    
    findKeyOf2({ a: 1, b: 2 }) // is 'b'
    findKeyOfB('ab') // is 1
    const findKeyOf2 = findKeyWithVal(2)
    const findKeyOfB = findKeyWithVal('b')
    
    findKeyOf2([1, 2, 3]) // is 1
    findKeyOf2([1, 2, 3, 2]) // is 1
    findKeyOf2([1, 3, 4]) // is undefined
    
    findKeyOf2({ a: 1, b: 2 }) // is 'b'
    findKeyOfB('ab') // is 1
    
  2. Sometimes we want to find the key to a value. Below, we have a raffle. Let's find the winner.

    const ticketHolders = {
      mike: 152876,
      luke: 961273,
      emma: 428670,
    }
    
    const winningTicket = 961273
    const findWinner = findKeyWithVal(winningTicket)
    const winner = findWinner(ticketHolders)
    
    console.log(winner)
    // is luke
    type TicketHolders = Record<string, number>
    const ticketHolders: TicketHolders = {
      mike: 152876,
      luke: 961273,
      emma: 428670,
    }
    
    const winningTicket = 961273
    const findWinner = findKeyWithVal(winningTicket)<TicketHolders>
    const winner = findWinner(ticketHolders)
    
    console.log(winner)
    // is luke
    
    const ticketHolders = {
      mike: 152876,
      luke: 961273,
      emma: 428670,
    }
    
    const winningTicket = 961273
    const findWinner = findKeyWithVal(winningTicket)
    const winner = findWinner(ticketHolders)
    
    console.log(winner)
    // is luke
    type TicketHolders = Record<string, number>
    const ticketHolders: TicketHolders = {
      mike: 152876,
      luke: 961273,
      emma: 428670,
    }
    
    const winningTicket = 961273
    const findWinner = findKeyWithVal(
      winningTicket
    )<TicketHolders>
    const winner = findWinner(ticketHolders)
    
    console.log(winner)
    // is luke