检查是否可以在另一个数组中找到所有项目 [英] Check if all items can be found in another array

查看:55
本文介绍了检查是否可以在另一个数组中找到所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查数组中的所有项目是否可以在另一个数组中找到.也就是说,我需要检查一个数组是否是另一个数组的子集.

I need to check if all items in an array can be found within another array. That is, I need to check if one array is a subset of another array.

示例:

var array = [1, 2, 5, 7];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

比较上面的两个数组应该返回true,因为 array 中的所有项目都可以在 otherArray 中找到.

Comparing these two arrays above should return true as all items in array can be found in otherArray.

var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

比较上面的两个数组应该返回false,因为在 otherArray 中找不到 array 中的一项.

Comparing these two arrays above should return false as one of the items in array cannot be found in otherArray.

我尝试在for循环内使用 indexOf 方法,但未成功.我希望有人能帮助我.:)

I have tried to use the indexOf method inside a for loop without success. I hope someone could help me. :)

推荐答案

使用

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

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

var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

var isSubset = array.every(function(val) {
  return otherArray.indexOf(val) >= 0;
})

document.body.innerHTML = "Is array a subset of otherArray? " + isSubset;

这篇关于检查是否可以在另一个数组中找到所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆