0

Consider the below scenario

const searchString = 'Gen';

const myDict = {
'Genesis': 'You are the beginning',
'Joel': 'Joe is cool'
 // Many other key value pairs
}

I need to get You are the beginning because searchString(Gen) is a substring of Genesis.

How can I achieve this in an optimized way in JS?

Nuthan
  • 3
  • 4
  • 1
    how would you do it in a not so optimized way? what have you tried? what goes wrong? – Nina Scholz Jun 24 '22 at 18:03
  • You could take a look at https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value and slightly modify some of the solutions – SuperStormer Jun 24 '22 at 18:04
  • @NinaScholz I had done it like this ```for (const key in myDict) { if (key.includes(searchString)) { console.log(myDict[key]); } }``` – Nuthan Jun 24 '22 at 18:12
  • @Nuthan, what is bad about this? – Nina Scholz Jun 24 '22 at 18:16
  • @NinaScholz I'm looping through the entire keys of the dictionary and checking if it includes the substring which defeats the purpose of having a dictionary(O(1) lookup) – Nuthan Jun 24 '22 at 18:21
  • the idea of hashes is to have that hash, not a part of it. – Nina Scholz Jun 24 '22 at 18:23
  • What should happen when the searchString is found in more than one key of myDict? – James Jun 24 '22 at 18:50
  • @James I don't have a case where the searchString is found in more than one key of myDict. Mapping of searchString to key of myDict is 1:1 – Nuthan Jun 25 '22 at 12:00

3 Answers3

0

You could do something like:

const searchString = 'Gen';

const myDict = {
'Genesis': 'You are the beginning',
'Joel': 'Joe is cool'
 // Many other key value pairs
}


for (let key in myDict){
    if(key.includes(searchString)){
        console.log(myDict[key]) // You are the beginning
    }
}
Felipe
  • 196
  • 2
  • 6
0

You could use find()

const searchString = 'Gen';

const myDict = {
'Genesis': 'You are the beginning',
'Joel': 'Joe is cool'
 // Many other key value pairs
}

const result = Object.entries(myDict).find(([k]) => k.includes(searchString));

console.log(result[1]);
axtck
  • 3,707
  • 2
  • 10
  • 26
0

const searchString = 'Gen';

const myDict = {
'Genesis': 'You are the beginning',
'Joel': 'Joe is cool'
 // Many other key value pairs
}

const result = Object.entries(myDict).find(([k]) => k.includes(searchString));

console.log(result[1]);
  • While reading up on Object.entries, I also found Object.keys where you can spare the destructuring. ```const key = Object.keys(myDict).find((key) => key.includes(searchString)); console.log(myDict[key]);``` – Nuthan Jun 24 '22 at 18:18
  • Can you please add some description or explaination around your code? It'll be helpful for the future readers to understand the algorithm you've used in your solution. – RBT Jun 25 '22 at 22:39