var myArray = [
["good morning", "am", "morning"],
["good night", "night", "evening"],
["good day", "day is good", "it's a good day"]
];
function compare(entry, string) {
for (var x in entry) {
strings = string.split(' ');
array1 = entry[x][0].split(' ');
if (strings.every(s => array1.indexOf(s) !== -1)) {
items = entry[x].slice(1);
return items
} else {
//return 'not found'
}
}
}
$("#input").keydown(function(e) {
keyword = $(this).val();
if (e.which === 13) {
$(this).val("");
text = keyword.toLowerCase();
result = '<div>' + compare(myArray, text) + '</div>'
$('#results').append(result);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input" type="text" placeholder="Search..." autocomplete="off" />
<div id="results" class="reset"></div>
strings = Keywords from input box is converted into an array
array1 = Each first items from group of arrays are converted into an array
...compare them then return items from the same group where it found the matched keywords. I used .slice(1) so it wont return the first item of each group.
Using every() is the closest iv got after trying includes(), .some() etc...
I have two problems on the above code:
- it will return undefined if the keyword is more than the words present in the array.
it should return true if keywords are:
good,
good morning dude,
good night folks,
good day people
- if I put "else" on the condition, it wont function same as without "else"...
thanks for your help..
String.prototype.includesrather than parsing out individual words? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…it will return undefined if the keyword is not present in the array.what should be the default return value in this case then?