Check if an array contains any element of another array in JavaScript

后端 未结 26 1151
礼貌的吻别
礼貌的吻别 2020-11-22 08:48

I have a target array [\"apple\",\"banana\",\"orange\"], and I want to check if other arrays contain any one of the target array elements.

For example:

26条回答
  •  太阳男子
    2020-11-22 09:02

    Vanilla JS with partial matching & case insensitive

    The problem with some previous approaches is that they require an exact match of every word. But, What if you want to provide results for partial matches?

    function search(arrayToSearch, wordsToSearch) {
        arrayToSearch.filter(v => 
            wordsToSearch.every(w => 
                v.toLowerCase().split(" ").
                    reduce((isIn, h) => isIn || String(h).indexOf(w) >= 0, false)
                )
            )
    }
    //Usage
    var myArray = ["Attach tag", "Attaching tags", "Blah blah blah"];
    var searchText = "Tag attach";
    var searchArr = searchText.toLowerCase().split(" "); //["tag", "attach"]
    
    var matches = search(myArray, searchArr);
    //Will return
    //["Attach tag", "Attaching tags"]
    

    This is useful when you want to provide a search box where users type words and the results can have those words in any order, position and case.

提交回复
热议问题