简体   繁体   English

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

[英]Check if array contains all elements of another array

I want a function that returns true if and only if a given array includes all the elements of a given "target" array.我想要一个 function 当且仅当给定数组包含给定“目标”数组的所有元素时才返回true As follows.如下。

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

How can I accomplish the above result?我怎样才能完成上述结果?

You can combine the .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)); // true console.log(checker(array3, array1)); // false

The every() method tests whether all elements in the array pass the test implemented by the provided function. every()方法测试数组中的所有元素是否通过提供的函数实现的测试。 It returns a Boolean value.它返回一个布尔值。 Stands to reason that if you call every() on the original array and supply to it a function that checks if every element in the original array is contained in another array, you will get your answer.理所当然地,如果您在原始数组上调用every()并向其提供一个检查原始数组中的每个元素是否包含在另一个数组中的函数,您将得到答案。 As such:像这样:

 const ar1 = ['a', 'b']; const ar2 = ['c', 'd', 'a', 'z', 'g', 'b']; if(ar1.every(r => ar2.includes(r))){ console.log('Found all of', ar1, 'in', ar2); }else{ console.log('Did not find all of', ar1, 'in', ar2); }

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]));

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]));

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

I had a similar question but not with two simple arrays.我有一个类似的问题,但不是两个简单的数组。 I wanted to check if all items from my array groceryList were included in the basket array consisting of fruit objects.我想检查数组groceryList中的所有项目groceryList都包含在由水果对象组成的basket数组中。

It checks for every groceryList item weather its value is in some fruit object property fruitType from my basket array.它会检查每个groceryList项目,其值是否在我的basket数组中的某个水果对象属性fruitType

Maybe this helps someone looking for a solution as I did.也许这有助于像我一样寻找解决方案的人。

 const groceryList = [ "apple", "cherry"] const basket = [{fruitType: "apple", amount: 3}, {fruitType: "cherry", amount: 20}, {fruitType: "blueberry", amount: 50}] console.log(groceryList, basket, groceryList.every(v => basket.some(w => w.fruitType === v)));

The below does the contains logic:下面执行包含逻辑:

function contains($superset, $subset) {
    foreach ($subset as $item) if (!in_array($item, $superset)) return true;
    return false;
}

Maybe it will help you, I have this method to validate if an object has a specific attribute也许它会帮助你,我有这个方法来验证对象是否具有特定属性

 function existFields(data: object, fields: string[]): boolean { return !fields .map((field) => Object.keys(data).includes(field)) .includes(Boolean(0)); } const data={"test":"a","test2":"b"}; const fields=["test"] console.log(existFields(data,fields))//True console.log(existFields(data,["test","test3"]))//False
 https://stackoverflow.com/questions/53606337/check-if-array-contains-all-elements-of-another-array#

reduce can be used here as well (but it has O = (N * M) difficulty): reduce 也可以在这里使用(但它有 O = (N * M) 难度):

const result = target.reduce((acc, el) => {
    return acc && array.includes(el)
}, true);

To solve this in more efficient way(O = N + M):为了以更有效的方式解决这个问题(O = N + M):

const myMap = new Map();

array.forEach(element => myMap.set(element);

const result = target.reduce((acc, el) => {
   return acc && myMap.has(el)
}, true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查一个数组是否包含另一个数组的所有元素 - How to check if an array contains all the elements of another another array 检查数组是否包含另一个数组的所有元素并获取索引作为回报 - Check if array contains all elements of another array AND get the index in return 使用 every() 检查一个数组是否包含另一个数组的所有元素 - Using every() to check if an Array contains all the elements of another Array 检查一个数组是否包含来自另一个数组的元素 - Check if an array contains elements from another array 检查数组包含另一个数组的每个元素 - check array contains every elements of another array 检查数组是否包含嵌套数组的所有元素 - Check if an array contains all the elements of an array that is nested 如何在JavaScript中检查一个数组是否包含另一个数组的所有元素,包括count? - How can I check it an array contains all elements from another array, including count, in JavaScript? 如何检查 Javascript 数组是否包含另一个数组的所有其他元素 - How do I check if a Javascript array contains all the other elements of another array 检查一个数组是否包含另一个数组的所有元素,包括重复是否出现两次 - Check to see if an array contains all elements of another array, including whether duplicates appear twice 检查一个javascript数组是否包含另一个数组的所有元素或元素值的一部分 - Check if a javascript array contains all elements or part of element values of another array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM