Home > Net >  Filter if array of strings matches partially
Filter if array of strings matches partially

Time:03-28

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.

CodePudding user response:

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)
    });
})

CodePudding user response:

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 .filter to iterate over the array (hayStack)
  • De-structure to directly access Title from 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 .some to iterate and find if any element is part of Title
  • Related