本文介绍了检查数组是否包含另一个数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个函数,当且仅当给定数组包含给定目标"的所有元素时返回 true
大批.如下.
I want a function that returns true
if and only if a given array includes all the elements of a given "target" array. 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?
推荐答案
您可以结合 .every()
和 .includes()
方法:
You can combine the .every()
and .includes()
methods:
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
这篇关于检查数组是否包含另一个数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!