I've an array of strings. I need to sort the array based on array of keywords.
The string containing max. number of keywords should come first and so on. Also, the string which contains max. no. of search keywords should come first than the number of occurrences of same search keyword. testArray should ignore case of searchTerms. If possible, you can ignore the strings which doesn't contain any search keywords in the result array.
var testArray = [
"I am",
"I am wrong and I don't know",
"I am right and I know",
"I don't know",
"I do know"
],
searchTerms = ["I", "right","know"];
$.each(searchTerms, function(index, term) {
var regX = new RegExp(term, "i");
testArray = $.map(testArray, function(item) {
if (regX.test(item)) {
return item;
} else {
return;
}
});
});
console.log(testArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you observe in the above code, the keywords are "I", "right","know". So the testArray results should be as below,
testArray = [
"I am right and I know",
"I am wrong and I don't know",
"I don't know",
"I do know",
"I am"
]
string contain all the keywords come first and the other strings contain "I","know", So they come next and string "I am" comes last as it contains only "I" keyword.