'Filter if array of strings matches partially
I want to filter array if it contains a particular string. It works as shown below. But I am not sure how to solve it if there are multiple strings to match. For example - instead of skillText = "Entry Level"; if we have skillText = ["Entry Level", "Scientist", "Analyst"];
var myList = [{"Title":"Entry Level - Data Analyst","Location":"Boston"}, {"Title":"Entry Level3 - Analyst","Location":"Delhi"}, {"Title":"Scientist","Location":"Boston"}];
skillText = "Entry Level";
result = myList.filter(function(v) {
return v["Title"].indexOf(skillText) > -1;
})
console.log(result);
For exact match skillText.includes(v["Title"]) works but not sure how to do with partial matches.
Solution 1:[1]
You can use the some function on arrays, it returns true if any of the items returns true from the callback
skillTexts = ["Entry Level", "Scientist"];
result = myList.filter(function(v) {
return skillTexts.some(function(skill) {
return v["Title"].includes(skill)
});
})
Solution 2:[2]
This may be one possible solution to achieve the desired objective:
Code Snippet
const findMatches = (hayStack, needle) => (
hayStack.filter(
({Title}) => (
[].concat(
needle
).some(
skill => Title.includes(skill)
)
)
)
);
const myList = [{"Title":"Entry Level - Data Analyst","Location":"Boston"}, {"Title":"Entry Level3 - Analyst","Location":"Delhi"}, {"Title":"Scientist","Location":"Boston"}];
let skillText = 'Entry Level';
console.log('searching text: "Entry Level"\nfound: ', findMatches(myList, skillText));
skillText = ['Level', 'Analyst', 'Scientist'];
console.log('searching array', skillText.join(), '\nfound: ', findMatches(myList, skillText));
Explanation
- Use
.filterto iterate over the array (hayStack) - De-structure to directly access
Titlefrom the iterator - To acccommodate
needle(search-text being a string or an array), first use[].concat()to obtain an array (This is done per pilchard's comment in the question above) - Use
.someto iterate and find if any element is part of Title
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
