[英]Compare arrays of sub-string
How can I check if an array of strings contains part of words stored in another array of strings ? 如何检查字符串数组是否包含存储在另一个字符串数组中的单词的一部分?
Let's say I've declared these three arrays : 假设我已经声明了这三个数组:
array1 = ["Lorem", "ipsum", "dolor" "sit" "amet"]
array2 = ["Lorem", "ipsum"]
keywords = ["ipsum", "dol"]
When comparing array1
with keywords
, I want to get something like true
because "ipsum"
and "dol"
are in array1
, but false
, when comparing array2
with keywords
because "dol"
isn't in array2
当比较带有
keywords
array1
时,我想得到类似true
东西,因为"ipsum"
和"dol"
在array1
,但是返回false
,当比较array2
与keywords
因为"dol"
不在array2
I searched for an hour, but I don't know how to do it... I succeeded to compare arrays with one keyword, but not with several keywords. 我搜索了一个小时,但是我不知道该怎么做...我成功地比较了带有一个关键字而不是多个关键字的数组。
.every()
) .every()
) .some()
) .some()
) .includes()
) .includes()
) Demo: 演示:
let array1 = ["Lorem", "ipsum", "dolor", "sit", "amet"], array2 = ["Lorem", "ipsum"], keywords = ["ipsum", "dol"]; let compare = (a, k) => k.every(s => a.some(v => v.includes(s))); console.log(compare(array1, keywords)); console.log(compare(array2, keywords));
Docs: 文件:
您可以使用Array.every
let contains = keywords.every(k => array1.findIndex(a => a.indexOf(k) > -1) > -1)
function arrayContains(array1,array2){
var res=0;
for (var i=0;i<array1.length;i++){
for (var j=0;i<array2.length;j++){
if (array1[i]==array2[j])
res++
}
}
return res==array2.length//if res is eqaul to array2.length then all elements of array2 are inside array1;
}
I would use indexOf
instead of includes
as includes
do not work in IE browsers. 我将使用
indexOf
而不是includes
includes
在IE浏览器中不起作用。 Browser compatibility 浏览器兼容性
let array1 = ["Lorem", "ipsum", "dolor", "sit", "amet"], array2 = ["Lorem", "ipsum"], keywords = ["ipsum", "dol"]; let compare = (a, k) => k.every(s => a.some(v => v.indexOf(s) !== -1)); console.log(compare(array1, keywords)); console.log(compare(array2, keywords));
var array1 = ['a','b','c'];
var array2 = ['g','f','h'];
var keys = ['a','g'];
function checkIfExists(key, arr) {
if (arr.indexOf(key) != -1) {
console.log('Key ' + key + ' exists in array');
} else {
console.log('Key ' + key + ' does not exists in array');
}
}
for (var i = 0; i < keys.length; i++) {
checkIfExists(keys[i], array1);
}
for (var i = 0; i < keys.length; i++) {
checkIfExists(keys[i], array2);
}
Output : 输出:
Key a exists in array Key g does not exists in array Key a does not exists in array Key g exists in array 键a在数组中存在键g在数组中不存在键a在数组中不存在键g在数组中存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.