-3

How do I find the first occurrence of a particular value in a Javascript Map? For example:

const m = new Map();
m.set("a", "b");
m.set("c", "d");
m.set("e", "f");
m.set("g", "f");

// Then I want to do something like this:
m.find_value((v) => v === "f");

Ideally it would return the key and value as a tuple (2-element array), i.e. ["e", "f"].

Obviously this is trivial to code manually with a for loop, but is there any neater built in way?

Timmmm
  • 88,195
  • 71
  • 364
  • 509

2 Answers2

1

There does not seem to be a better way than writing it myself, like a commoner.

function find_map_value<K, V>(m: Map<K, V>, predicate: (v: V) => boolean): [K, V] | undefined {
  for (const [k, v] of m.entries()) {
    if (predicate(v)) {
        return [k, v];
    }
  }
  return undefined;
}
Timmmm
  • 88,195
  • 71
  • 364
  • 509
-2

const m = new Map();
m.set("a", "b");
m.set("c", "d");
m.set("e", "f");
m.set("g", "f");

Map.prototype.find_value = function (predicate) { 
  return Array.from(this.entries())
    .find(([, v]) => predicate(v)) }

// Then I want to do something like this:
const result = m.find_value((v) => v === "f");

console.log(result)
bel3atar
  • 913
  • 4
  • 6