在 JavaScript 中检查一个数组是否包含另一个数组的任何元素
2013-05-01
1171447
我有一个目标数组
["apple","banana","orange"]
,我想检查其他数组是否包含任何一个目标数组元素。
例如:
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
我如何在 JavaScript 中做到这一点?
3个回答
Vanilla JS
ES2016:
const found = arr1.some(r=> arr2.includes(r))
工作原理
some(..)
根据测试函数检查数组的每个元素,如果数组中的任何元素通过测试函数,则返回 true,否则返回 false。如果数组中存在给定的参数,则
includes(..)
均返回 true。
Paul Grimshaw
2016-10-06
vanilla 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;
});
};
正如 @loganfsmyth 所指出的,您可以在 ES2016 中将其缩短为
/**
* @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.
*/
const findOne = (haystack, arr) => {
return arr.some(v => haystack.includes(v));
};
或者简单地缩短为
arr.some(v => haystack.includes(v));
如果您想确定数组是否包含来自另一个数组的所有项目,请将
some()
替换为
every()
或替换为
arr.every(v => haystack.includes(v));
skyisred
2014-09-19
ES6 解决方案:
let arr1 = [1, 2, 3];
let arr2 = [2, 3];
let isFound = arr1.some( ai => arr2.includes(ai) );
或者,如果必须包含所有值:
let allFound = arr2.every( ai => arr1.includes(ai) );
protanvir993
2019-07-14