检查一个数组是否包含 JavaScript 中另一个数组的任何元素香草 js

2022-08-29 22:29:13

我有一个目标数组,我想检查其他数组是否包含任何一个目标数组元素。["apple","banana","orange"]

例如:

["apple","grape"] //returns true;

["apple","banana","pineapple"] //returns true;

["grape", "pineapple"] //returns false;

我怎样才能在 JavaScript 中做到这一点?


答案 1

香草 JS

ES2016:

const found = arr1.some(r=> arr2.includes(r))

ES6:

const found = arr1.some(r=> arr2.indexOf(r) >= 0)

它是如何运作的

一些(..)根据测试函数检查数组的每个元素,如果数组的任何元素通过测试函数,则返回 true,否则返回 false。indexOf(..) >= 0include(..) 如果数组中存在给定的参数,则两者都返回 true。


答案 2

香草 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));

如果要确定数组是否包含其他数组中的所有项,请将 替换为 或 assome()every()arr.every(v => haystack.includes(v));