1

How can I apply an array to a lookup dictionary in Javascript? Example:

lookup = {"milk": 1, "water": 2, "soda": 3};
my_array = ["milk", "milk", "water", "milk", "soda"];

my_array.??? // This should give [1, 1, 2, 1, 3]

I've tried my_array.map(lookup) and I get #<Object> is not a function. Same with .filter(), .apply() and the other obvious candidates.

user1717828
  • 7,122
  • 8
  • 34
  • 59
  • @TrentonTrama N- no? Not even close? You issued a _Close As Duplicate_ vote for this? Am I missing something or is filtering an object the same as mapping an array with an object? – user1717828 Feb 10 '20 at 02:37

1 Answers1

4

You need array.map() but you have to specify a function which transforms single my_array element:

let lookup = {"milk": 1, "water": 2, "soda": 3};
let my_array = ["milk", "milk", "water", "milk", "soda"];

let result = my_array.map(x => lookup[x]);
console.log(result);
mickl
  • 48,568
  • 9
  • 60
  • 89