Recently, I've embarked on a journey to learn javascript and ventured into developing a small chrome extension. This extension aims to scan item listings on a specific website for products that match keywords provided by users. I am seeking guidance on an approach to compare a string against an array of strings.
Here are the variables in question:
var itemDetails = '[alter] saber 1/8 figure unopened';
var trackingList = ['alter figure', 'magic', 'sword art'];
The task at hand is to determine if any of the strings in trackingList are present in itemDetails. While I can utilize indexOf()
as follows:
function checkArray(str, arr){
for(var i=0; i < arr.length; i++){
if(str.indexOf(arr[i]) > -1)
return true;
}
return false;
}
checkArray(itemDetails,trackingList); // returns false
I desire a scenario where a multi-word string like 'alter figure' will return true if all words appear somewhere within itemDetails. Hence, in the above example, checkArray()
should evaluate to true since both 'alter' and 'figure' are found in itemDetails
.
My current approach involves splitting each element in the trackingList
:
function splitTrackList(arr){
var newarr = [];
for(var i = 0; i < arr.length; i++){
newarr[i] = arr[i].split(" ");
}
return newarr;
}
trackList = splitTrackList(trackList);
// [['alter', 'figure'], ['magic'], ['sword', 'art']]
Subsequently, comparison is then made using indexOf()
:
function newCheckArray(str, arr){
var passed = true;
for(var i=0; i < arr.length; i++){
for(var j=0; j < arr[i].length; j++){
if(str.indexOf(arr[i][j]) == -1){
passed = false;
break;
}
else passed = true;
}
if(passed) //stop loop if match found
break;
}
return passed;
}
newCheckArray(itemDetails,trackingList); //returns true
While my method yields results, I suspect there might be a more efficient way to achieve this. Your insights and suggestions would be greatly appreciated. Thank you in advance.