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'
Solution 1:
- For every element in keywords array (use
.every()
) - There must be some element in other array (use
.some()
) - That includes the string currently in consideration (use
.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:
Solution 2:
You can use Array.every
let contains = keywords.every(k => array1.findIndex(a => a.indexOf(k) > -1) > -1)
Solution 3:
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;
}
Solution 4:
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));
Solution 5:
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
Post a Comment for "Compare Arrays Of Sub-string"