Search code examples
javascriptarraysreplacelookup

Replace values in array based on lookup table - javascript


I have a long array which has shorthand ID's which I want to replace with the full values from a lookup

Here's the original array

const original = 
[ [ '18', 'v'],
  [ '20', 'aev'],
  [ '22', 'v'],
  [ '23', 'v'],
  [ '25', 'c'],
  [ '29', 'vv'],
  [ '30', 'c'] ]

The lookup

const lookup = {'v' : 'monkey', 'aev' : 'dog', 'c' : 'cow', 'vv': 'lion'};

The result I want to see

const result = 
[ [ '18', 'monkey'],
  [ '20', 'dog'],
  [ '22', 'monkey'],
  [ '23', 'monkey'],
  [ '25', 'cow'],
  [ '29', 'lion'],
  [ '30', 'cow'] ] 

I'm not sure if I should use a map function or for loop and how this would look exactly.

I've tried multiple versions of for loops, but I can't get to the result, because I'm not returning the exact match (it picks up v (monkey) instead of the aev value (dog))


Solution

  • const original = [ 
      [ '18', 'v'],
      [ '20', 'aev'],
      [ '22', 'v'],
      [ '23', 'v'],
      [ '25', 'c'],
      [ '29', 'vv'],
      [ '30', 'c'] ]
    
    const lookUp = {'v' : 'monkey', 'aev' : 'dog', 'c' : 'cow', 'vv': 'lion'};  
    
    const result = original.map(item => [item[0], lookUp[item[1]]])
    console.log(result)