Javascript 检查数组是否包含另一个数组的所有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53606337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:08:46  来源:igfitidea点击:

Check if array contains all elements of another array

javascriptarrays

提问by lakshay bakshi

Target array [1,2,3]

目标阵列 [1,2,3]

array1 = [1,2,3]; //return true
array2 = [1,2,3,4]; //return true
array3 = [1,2] //return false

i am not getting how to achieve this or may be need to use custom login in this. I have used some and include but that doesn't work for me.

我不知道如何实现这一点,或者可能需要在此使用自定义登录。我已经使用了一些并包含,但这对我不起作用。

回答by Mohammad Usman

You can use .every()and .includes()methods:

您可以使用.every().includes()方法:

let array1 = [1,2,3],
    array2 = [1,2,3,4],
    array3 = [1,2];

let checker = (arr, target) => target.every(v => arr.includes(v));

console.log(checker(array2, array1));
console.log(checker(array3, array1));

回答by Mamun

You can try with Array.prototype.every():

您可以尝试Array.prototype.every()

The every()method tests whether all elements in the array pass the test implemented by the provided function.

every()方法测试数组中的所有元素是否通过提供的函数实现的测试。

and Array.prototype.includes():

Array.prototype.includes()

The includes()method determines whether an array includes a certain element, returning true or false as appropriate.

includes()方法确定数组是否包含某个元素,根据情况返回 true 或 false。

var mainArr = [1,2,3];
function isTrue(arr, arr2){
  return arr.every(i => arr2.includes(i));
}
console.log(isTrue(mainArr, [1,2,3]));
console.log(isTrue(mainArr, [1,2,3,4]));
console.log(isTrue(mainArr, [1,2]));

回答by zetawars

If you are using ES5, then you can simply do this.

如果您使用的是 ES5,那么您可以简单地执行此操作。

targetArray =[1,2,3]; 
array1 = [1,2,3]; //return true
array2 = [1,2,3,4]; //return true
array3 = [1,2] //return false

console.log(targetArray.every(function(val) { return array1.indexOf(val) >= 0; })); //true
 console.log(targetArray.every(function(val) { return array2.indexOf(val) >= 0; })); // true
 console.log(targetArray.every(function(val) { return array3.indexOf(val) >= 0; }));// false

回答by Pankaj Revagade

I used Purely Javascript.

我使用纯 Javascript。

function checkElementsinArray(fixedArray,inputArray)
{
    var fixedArraylen = fixedArray.length;
    var inputArraylen = inputArray.length;
    if(fixedArraylen<=inputArraylen)
    {
        for(var i=0;i<fixedArraylen;i++)
        {
            if(!(inputArray.indexOf(fixedArray[i])>=0))
            {
                return false;
            }
        }
    }
    else
    {
        return false;
    }
    return true;
}

console.log(checkElementsinArray([1,2,3], [1,2,3]));
console.log(checkElementsinArray([1,2,3], [1,2,3,4]));
console.log(checkElementsinArray([1,2,3], [1,2]));