Reputation:
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
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.
Upvotes: 1
Views: 126
Reputation: 39322
.every()
).some()
).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:
Upvotes: 4
Reputation: 30739
I would use indexOf
instead of includes
as includes
do not work in IE browsers. 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));
Upvotes: 0
Reputation: 871
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
Upvotes: -1
Reputation: 14389
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;
}
Upvotes: 0
Reputation: 104775
You can use Array.every
let contains = keywords.every(k => array1.findIndex(a => a.indexOf(k) > -1) > -1)
Upvotes: 3