檢查一個數組是否包含JavaScript中另一個數組的任何元素

本文翻譯自:Check if an array contains any element of another array in JavaScript

I have a target array ["apple","banana","orange"] , and I want to check if other arrays contain any one of the target array elements. 我有一個目標數組["apple","banana","orange"] ,我想檢查其他數組是否包含任何目標數組元素。

For example: 例如:

["apple","grape"] //returns true;

["apple","banana","pineapple"] //returns true;

["grape", "pineapple"] //returns false;

How can I do it in JavaScript? 如何在JavaScript中完成?


#1樓

參考:https://stackoom.com/question/16RdI/檢查一個數組是否包含JavaScript中另一個數組的任何元素


#2樓

If you don't need type coercion (because of the use of indexOf ), you could try something like the following: 如果不需要類型強制(由於使用indexOf ),則可以嘗試以下操作:

var arr = [1, 2, 3];
var check = [3, 4];

var found = false;
for (var i = 0; i < check.length; i++) {
    if (arr.indexOf(check[i]) > -1) {
        found = true;
        break;
    }
}
console.log(found);

Where arr contains the target items. 其中arr包含目標項目。 At the end, found will show if the second array had at least one match against the target. 最後, found將顯示第二個數組是否與目標至少有一個匹配項。

Of course, you can swap out numbers for anything you want to use - strings are fine, like your example. 當然,您可以將數字換成任何您想使用的東西-字符串很好,例如您的示例。

And in my specific example, the result should be true because the second array's 3 exists in the target. 在我的特定示例中,結果應該爲true因爲目標中存在第二個數組3


UPDATE: 更新:

Here's how I'd organize it into a function (with some minor changes from before): 這是我將其組織成一個函數的方式(與之前相比有一些細微的變化):

var anyMatchInArray = (function () {
    "use strict";

    var targetArray, func;

    targetArray = ["apple", "banana", "orange"];
    func = function (checkerArray) {
        var found = false;
        for (var i = 0, j = checkerArray.length; !found && i < j; i++) {
            if (targetArray.indexOf(checkerArray[i]) > -1) {
                found = true;
            }
        }
        return found;
    };

    return func;
}());

DEMO: http://jsfiddle.net/u8Bzt/ 演示: http : //jsfiddle.net/u8Bzt/

In this case, the function could be modified to have targetArray be passed in as an argument instead of hardcoded in the closure. 在這種情況下,可以修改該函數以使targetArray作爲參數傳遞,而不是在閉包中進行硬編碼。


UPDATE2: UPDATE2:

While my solution above may work and be (hopefully more) readable, I believe the "better" way to handle the concept I described is to do something a little differently. 儘管我上面的解決方案可能會起作用,並且(希望是)可讀性更高,但我認爲處理我所描述的概念的“更好”的方法是做一些不同的事情。 The "problem" with the above solution is that the indexOf inside the loop causes the target array to be looped over completely for every item in the other array. 上述解決方案的“問題”是循環內的indexOf導致目標數組針對另一個數組中的每個項完全循環。 This can easily be "fixed" by using a "lookup" (a map...a JavaScript object literal). 通過使用“查找”(映射... JavaScript對象文字),可以輕鬆地“修復”此問題。 This allows two simple loops, over each array. 這允許在每個數組上進行兩個簡單的循環。 Here's an example: 這是一個例子:

var anyMatchInArray = function (target, toMatch) {
    "use strict";

    var found, targetMap, i, j, cur;

    found = false;
    targetMap = {};

    // Put all values in the `target` array into a map, where
    //  the keys are the values from the array
    for (i = 0, j = target.length; i < j; i++) {
        cur = target[i];
        targetMap[cur] = true;
    }

    // Loop over all items in the `toMatch` array and see if any of
    //  their values are in the map from before
    for (i = 0, j = toMatch.length; !found && (i < j); i++) {
        cur = toMatch[i];
        found = !!targetMap[cur];
        // If found, `targetMap[cur]` will return true, otherwise it
        //  will return `undefined`...that's what the `!!` is for
    }

    return found;
};

DEMO: http://jsfiddle.net/5Lv9v/ 演示: http : //jsfiddle.net/5Lv9v/

The downside to this solution is that only numbers and strings (and booleans) can be used (correctly), because the values are (implicitly) converted to strings and set as the keys to the lookup map. 該解決方案的缺點是隻能(正確)使用數字和字符串(以及布爾值),因爲(隱式)將值轉換爲字符串並將其設置爲查找映射的鍵。 This isn't exactly good/possible/easily done for non-literal values. 對於非文字值來說,這不是完全好/可能/容易做到的。


#3樓

If you're not opposed to using a libray, http://underscorejs.org/ has an intersection method, which can simplify this: 如果您不反對使用libray,則http://underscorejs.org/具有交叉方法,可以簡化此操作:

var _ = require('underscore');

var target = [ 'apple', 'orange', 'banana'];
var fruit2 = [ 'apple', 'orange', 'mango'];
var fruit3 = [ 'mango', 'lemon', 'pineapple'];
var fruit4 = [ 'orange', 'lemon', 'grapes'];

console.log(_.intersection(target, fruit2)); //returns [apple, orange]
console.log(_.intersection(target, fruit3)); //returns []
console.log(_.intersection(target, fruit4)); //returns [orange]

The intersection function will return a new array with the items that it matched and if not matches it returns empty array. 相交函數將返回一個帶有匹配項的新數組,如果不匹配,則返回空數組。


#4樓

It can be done by simply iterating across the main array and check whether other array contains any of the target element or not. 這可以通過簡單地遍歷主數組並檢查其他數組是否包含任何目標元素來完成。

Try this: 嘗試這個:

function Check(A) {
    var myarr = ["apple", "banana", "orange"];
    var i, j;
    var totalmatches = 0;
    for (i = 0; i < myarr.length; i++) {
        for (j = 0; j < A.length; ++j) {
            if (myarr[i] == A[j]) {

                totalmatches++;

            }

        }
    }
    if (totalmatches > 0) {
        return true;
    } else {
        return false;
    }
}
var fruits1 = new Array("apple", "grape");
alert(Check(fruits1));

var fruits2 = new Array("apple", "banana", "pineapple");
alert(Check(fruits2));

var fruits3 = new Array("grape", "pineapple");
alert(Check(fruits3));

DEMO at JSFIDDLE JSFIDDLE的演示


#5樓

With underscorejs 使用underscorejs

var a1 = [1,2,3];
var a2 = [1,2];

_.every(a1, function(e){ return _.include(a2, e); } ); //=> false
_.every(a2, function(e){ return _.include(a1, e); } ); //=> true

#6樓

vanilla js 香草js

/**
 * @description determine if an array contains one or more items from another array.
 * @param {array} haystack the array to search.
 * @param {array} arr the array providing items to check for in the haystack.
 * @return {boolean} true|false if haystack contains at least one item from arr.
 */
var findOne = function (haystack, arr) {
    return arr.some(function (v) {
        return haystack.indexOf(v) >= 0;
    });
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章