skip to Main Content

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))

3

Answers


  1. 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)
    Login or Signup to reply.
  2. You can use map with destructuring syntax

    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(([id, shorthand]) => [id, lookup[shorthand]]);
    
    console.log(result);
    Login or Signup to reply.
  3. You can create a new array and push the desired elements on it like this:

    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) => {
      result.push([item[0], lookUp[item[1]]])
    })
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search