检查一个数组是否包含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;
    });
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值