Skip to content
Advertisement

I need a to get a value in a map so that its key that includes a value

I want to do something like:

MyMap.set(['milk', 'eggs', 'flour'], 'ingredients');
MyMap.set(['red', 'green', 'blue'], 'colors');

console.log(MyMap.get(ELEMENT THAT INCLUDES eggs));
//expected: ingredients

I’ve tried a bunch of stuff, like using Array.has() and Array.includes(), but I just can’t. I’m new here and in coding, so sorry if i messed something up or if the solution is absurdly easy.

Advertisement

Answer

Map Api doesn’t support anything of this sort out of the box. Here is one of the ways you can get it done.

let MyMap = new Map();
MyMap.set(['milk', 'eggs', 'flour'], 'ingredients');
MyMap.set(['red', 'green', 'blue'], 'colors');
let valuesWhoseKeyIncludeText = [];
MyMap.forEach((value, key) => {
  if (key.includes('eggs')) {
    valuesWhoseKeyIncludeText.push(value);
  }
});
console.log(valuesWhoseKeyIncludeText);

//Above code returns Array of values whose key includes given text.
//So  if you have multiple entries in Map whose key includes given text then you will get array of values as result. e.g

let MyMap2 = new Map();
MyMap2.set(['milk', 'eggs', 'flour'], 'ingredients');
MyMap2.set(['red', 'green', 'blue'], 'colors');
MyMap2.set(['red', 'eggs', 'flour'], 'ingredientsAndColors');
let valuesWhoseKeyIncludeText2 = [];
MyMap2.forEach((value, key) => {
  if (key.includes('eggs')) {
    valuesWhoseKeyIncludeText2.push(value);
  }
});
console.log(valuesWhoseKeyIncludeText2);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement