Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading