通过数组中任何单词的前两个字母在数组中搜索

search in array by the first two letters of any word within an array

使用下面的数组,我想搜索第一个字母假设在同一个矩阵中有几个单词,它必须在每个单词中搜索,如果找到它应该在数组中 return

例子

const data= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ]
]

如果它匹配“sh”,它应该搜索每个单词并且 return

["Shutter Island", "The Truman Show"] but not The Gold Rush

如果它匹配“狮子”,它应该搜索每个词并且 return

["the lions of teranga"]

这是 forEachRegEx

组合的解决方案之一

const data= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ]
  
const filteredData = []


data.forEach(sentence => {
    let words = sentence.split(" ")
    words.forEach((word,index) => {
      if(word.match(/^lions?\w/gi)) {
        filteredData.push(sentence)
      }
    })
    
})

console.log(filteredData)

const data= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ]
inputData = "lions"
let a = data.filter(e => {
    str = e.toLowerCase()
    if (str.match(inputData.toLowerCase())){
        return e
    }
})
console.log(a)

此处过滤 return 为 return 的对象。在这里您可以按任何单词或字符进行搜索,并且 return 作为数组进行搜索。

//your data array
const data= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ];
    //your search letters,if it will be the same use const instead of var
    var search="sh";
    //make your search case insensitive
    search=search.toLowerCase()
    //use for loop to go through every sentence
    for(var counter=0;counter<data.length;counter++)
    {
       //get the array of words
       var arrayOfWords=data[counter].match(/\b(\w+)\b/g);
       
       //use for loop to go through every word
       for(var counter2=0;counter2<arrayOfWords.length;counter2++)
       {
          //make word case insensitive
          var tempWord=arrayOfWords[counter2].toLowerCase();
          //check if the search length does not exid your actuall word
          if(search.length<=tempWord.length)
          {
             //check if first letters match
             if(tempWord.slice(0,search.length==search)
             {
                //first letters match, you can put your logic here
             }
             else
             {
                //no match
             }
          }
          else
          {
             //search exids word
          }
       }
    }