-1

I searched a lot on the internet and didn't find any answer to solve my problem.

I have an object with several keys and values.

const replies = {
"Hello": ['Hi', 'Whats up', 'Aloha'],
"See you": ['Goodbye', 'exit']
};

My string is

Var sentence = "Hi my friend";

I would like a function that returns the key of "replies" if the "sentence" contains some value from it. Something like:

function search(replies, sentence){
var reply = sentence.includes(replies);
return reply //output is Hello key
}

1 Answers1

1

Explanations throughout the code below.

const replies = {
"Hello": ['Hi', 'Whats up', 'Aloha'],
"See you": ['Goodbye', 'exit']
};
var sentence = "Hi my friend";

// Get the replies keys in an array
let keys = Object.keys(replies);

// Then, each key holds an array... Loop it to compare against the sentance
let hits = keys.map(function(key){
  return replies[key].map(function(word){
    return sentence.includes(word) ? key : null
  })
})

// You will get an array structured like replies
console.log(hits)

// Flatten it and filter out the nulls
let result = hits.flat().filter(item=>item)

// Your expected result as a array
console.log(result)
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64