-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
}
0

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.