Then we can use the
filter method to return an array with the entries with the given value.
For instance, we can write:
const people = new Map(); people.set('1', 'john'); people.set('2', 'jasmin'); people.set('3', 'foo'); const keys = [...people.entries()] .filter(([, v]) => v === 'john') .map(([k]) => k); console.log(keys);
We create the
people map with a few entries.
And we want to find the key for the entry with
'john' as its value.
To do this, we call
people.entries() to return an iterator with the key-value pair arrays from the map.
Then we spread the iterator entries into an array with the spread operator.
Next, we call
filter with a callback that destructures the
v map value from the parameter.
And we return the entries where value
Finally, we call
map to map the
k keys from the map and return them in the returned array.
["1"] as we can see from the console log.