我有一个目标数组[“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中实现?
当前回答
添加到阵列原型
免责声明:许多人强烈建议不要这样做。唯一真正有问题的是,如果一个库添加了一个同名(行为不同)的原型函数或类似的东西。
代码:
Array.prototype.containsAny = function(arr) {
return this.some(
(v) => (arr.indexOf(v) >= 0)
)
}
不使用大箭头功能:
Array.prototype.containsAny = function(arr) {
return this.some(function (v) {
return arr.indexOf(v) >= 0
})
}
用法
var a = ["a","b"]
console.log(a.containsAny(["b","z"])) // Outputs true
console.log(a.containsAny(["z"])) // Outputs false
其他回答
ES6(最快)
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v=> b.indexOf(v) !== -1)
2016年
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
良好的性能解决方案:
我们应该将其中一个数组转换为对象。
const contains = (arr1, mainObj) => arr1.some(el => el in mainObj);
const includes = (arr1, mainObj) => arr1.every(el => el in mainObj);
用法:
const mainList = ["apple", "banana", "orange"];
// We make object from array, you can use your solution to make it
const main = Object.fromEntries(mainList.map(key => [key, true]));
contains(["apple","grape"], main) // => true
contains(["apple","banana","pineapple"], main) // => true
contains(["grape", "pineapple"], main) // => false
includes(["apple", "grape"], main) // => false
includes(["banana", "apple"], main) // => true
您可能会面临由in运算符检查的一些缺点(例如{}//=>true中的“toString”),因此您可以将解决方案更改为obj[key]检查器
一个简短的写法:找到常量=arr1.some(arr2.includes)
这是一个有趣的案例,我认为我应该分享。
假设您有一个对象数组和一个选定过滤器数组。
let arr = [
{ id: 'x', tags: ['foo'] },
{ id: 'y', tags: ['foo', 'bar'] },
{ id: 'z', tags: ['baz'] }
];
const filters = ['foo'];
要将所选过滤器应用于此结构,我们可以
if (filters.length > 0)
arr = arr.filter(obj =>
obj.tags.some(tag => filters.includes(tag))
);
// [
// { id: 'x', tags: ['foo'] },
// { id: 'y', tags: ['foo', 'bar'] }
// ]
我在node中使用下划线js提出了一个解决方案,如下所示:
var checkRole = _.intersection(['A','B'], ['A','B','C']);
if(!_.isEmpty(checkRole)) {
next();
}