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

前端 未结 2 1251
攒了一身酷
攒了一身酷 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: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))

提交回复
热议问题