我有一个目标数组["apple","banana","orange"]
,我想检查其他数组是否包含任何一个目标数组元素。
例如:
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
我如何在 JavaScript 中做到这一点?
我有一个目标数组["apple","banana","orange"]
,我想检查其他数组是否包含任何一个目标数组元素。
例如:
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
我如何在 JavaScript 中做到这一点?
香草JS
ES2016:
const found = arr1.some(r=> arr2.includes(r))
ES6:
const found = arr1.some(r=> arr2.indexOf(r) >= 0)
怎么运行的
some(..)
根据测试函数检查数组的每个元素,如果数组的任何元素通过测试函数,则返回 true,否则返回 false。如果给定的参数存在于数组中indexOf(..) >= 0
,则includes(..)
两者都返回 true。
/**
* @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));
ES6解决方案:
let arr1 = [1, 2, 3];
let arr2 = [2, 3];
let isFounded = arr1.some( ai => arr2.includes(ai) );
与它不同的是:必须包含所有值。
let allFounded = arr2.every( ai => arr1.includes(ai) );
希望,会有所帮助。
如果你不反对使用 libray,http ://underscorejs.org/有一个交集方法,它可以简化这个:
var _ = require('underscore');
var target = [ 'apple', 'orange', 'banana'];
var fruit2 = [ 'apple', 'orange', 'mango'];
var fruit3 = [ 'mango', 'lemon', 'pineapple'];
var fruit4 = [ 'orange', 'lemon', 'grapes'];
console.log(_.intersection(target, fruit2)); //returns [apple, orange]
console.log(_.intersection(target, fruit3)); //returns []
console.log(_.intersection(target, fruit4)); //returns [orange]
交叉函数将返回一个新数组,其中包含匹配的项目,如果不匹配,则返回空数组。
ES6(最快)
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v=> b.indexOf(v) !== -1)
ES2016
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v => b.includes(v));
下划线
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
_.intersection(a, b)
演示:https : //jsfiddle.net/r257wuv5/
jsPerf:https ://jsperf.com/array-contains-any-element-of-another-array