Reputation: 7223
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.
Upvotes: 1
Views: 46
Reputation: 49985
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);
Upvotes: 4