Compare/filter two arrays where array B contains any substring of A

前端 未结 2 1224
攒了一身酷
攒了一身酷 2021-01-14 05:35

Okay, so this is something i partially have working (ignoring case sensitivity) comparing the following:

arrayA = [\"apples\", \"Oranges\", \"salt\", \"Crack         


        
相关标签:
2条回答
  • 2021-01-14 06:00

    Since arrayB contains the "needles", and arrayA contains the "haystacks", so to speak, you can use String.prototype.includes(). Note you are actually using Array.prototype.includes() in your attempt, which is why it only matches "salt" (based on your example code, I am highly doubtful that even "orange" was a successful match).

    Below is a solution that uses String.prototype.includes() instead:

    function matchedSubstrings (haystacks, needles) {
      return needles.filter(function (needle) {
        const lowerCaseNeedle = needle.toLowerCase()
        return this.some(haystack => haystack.includes(lowerCaseNeedle))
      }, haystacks.map(haystack => haystack.toLowerCase()))
    }
    
    const arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"]
    const arrayB = ["Salt", "pepper", "orange"]
    
    console.log(matchedSubstrings(arrayA, arrayB))

    The this of the Array.prototype.filter() callback function is the transformed haystacks array passed as the second argument.

    The equivalent TypeScript is as follows:

    function matchedSubstrings (haystacks: string[], needles: string[]): string[] {
      return needles.filter(function (this: string[], needle) {
        const lowerCaseNeedle = needle.toLowerCase()
        return this.some(haystack => haystack.includes(lowerCaseNeedle))
      }, haystacks.map(haystack => haystack.toLowerCase()))
    }
    
    const arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"]
    const arrayB = ["Salt", "pepper", "orange"]
    
    console.log(matchedSubstrings(arrayA, arrayB))
    
    0 讨论(0)
  • 2021-01-14 06:09

    You can use filter and some. with regex

    • Filter is used to get desired values only.
    • Some is used to check if any of values in arrayA matches with current element.
    • Regex is used to match the string. i flag is used for case insensitivity.

    let arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"];
    let arrayB = ["salt", "pepper", "orange"]
    
    let find = (A,B) => {
      return B.filter(b=> A.some(a=> new RegExp(b,'i').test(a)))
    }
    
    console.log(find(arrayA,arrayB))

    0 讨论(0)
提交回复
热议问题