0

I'm trying to find a way to look into a Map array value to see if it exists if it does return the Map key as a variable. this has stumped me for a bit now as I don't do much javascript.

const map = new Map([
        ["KEY1", ["dummy1","dummy2","dummy3"]],
        ["KEY2", ["dummy4","dummy5","dummy6","dummy7"]],
        ["KEY3", ["dummy8","dummy9"]],
    ]);

so say I have dummy4 as a var I want to look in map and see it there in the array of values with key2 and return the key into a new variable of sting "KEY2"

hopbop
  • 13
  • 3
  • but `KEY2` does not contain a value `key2` – Jaromanda X Dec 18 '20 at 02:21
  • If you're doing a lot of lookups on this and need it to be quick, consider "inverting" the structure. Make a table of form `value => key`. – tadman Dec 18 '20 at 02:26
  • Can you explain why you are doing this? This completely goes against the way a Map is meant to be used. – Mulan Dec 18 '20 at 02:26
  • 1
    exactly what @tadman said. if this is a one-off or for debugging purposes it's probably okay, but if this is normal way you expect to use Maps or if the operation appears in a loop you should reconsider the structure. – Mulan Dec 18 '20 at 02:28
  • I'm doing it this way to search for a certain value that could have many terms it might not be the best way its what I cam up with basically many values could be entered into an input but all relate to only one output – hopbop Dec 18 '20 at 02:29

2 Answers2

1

Loop through the entries:

function findValue(map, value) {
    for (const [k, arr] of map.entries()) {
        if (arr.includes(value)) {
            return k;
        }
    }
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

I'm doing it this way to search for a certain value that could have many terms it might not be the best way its what I cam up with basically many values could be entered into an input but all relate to only one output

Based on a comment, I'm going to recommend a different way to build your lookup structure -

const terms =
  [ ["KEY1", ["dummy1","dummy2","dummy3"]]
  , ["KEY2", ["dummy4","dummy5","dummy6","dummy7"]]
  , ["KEY3", ["dummy8","dummy9"]]
  ]
  
const dict =
  new Map(terms.flatMap(([ k, vs ]) => vs.map(v => [ v, k ])))
  
console.log(dict.get("dummy2"))
console.log(dict.get("dummy5"))
console.log(dict.get("dummy7"))
console.log(dict.get("dummy9"))
console.log(dict.get("dummy0"))

Output -

KEY1
KEY2
KEY2
KEY3
undefined

This is more efficient because the Map structure provides instant lookup for any value and does not require a full .entries scan -

Map
  { "dummy1" -> "KEY1"
  , "dummy2" -> "KEY1"
  , "dummy3" -> "KEY1"
  , "dummy4" -> "KEY2"
  , "dummy5" -> "KEY2"
  , "dummy6" -> "KEY2"
  , "dummy7" -> "KEY2"
  , "dummy8" -> "KEY3"
  , "dummy9" -> "KEY3"
  }
Mulan
  • 129,518
  • 31
  • 228
  • 259