How do I search a string for keywords found in multi-dimensional array?
So I have some data that looks like this:
stringToSearch = 'this string needs to be searched';
labels = ['keys 1-3','keys 4-6','keys 7-9'];
keywords =
['key1', 'key2', 'key3'],
['key4', 'key5', 'key6'],
['key7', 'key8', 'key9']
];
EDIT: Basically what I'm trying to 开发者_如何学运维achieve is, searching the string for any of the keys. Then finding the all of the labels that correspond with the groups that the keys are in.
EDIT: The goal is to pass in the string and get back the labels.
string='this contains key5 and key9';
So it returns, labels 'key 4-6' and 'keys 7-9'
Try this:
stringsToSearch = ['this string needs to be searched', '...']
keywords = {
firstGroup: {
key1: [],
key2: [],
key3: []
},
secondGroup: {
key4: [],
key5: [],
key6: []
},
thirdGroup: {
key7: [],
key8: [],
key9: []
}
}
$.each(keywords, function(groupName, keyGroup) {
$.each(keyGroup, function(key, foundStrings) {
$.each(stringsToSearch, function() {
if(this.search(key) >= 0)
foundStrings.push(this);
});
});
});
Here's another solution, based off your most recent edit:
stringToSearch = 'this string needs to be searched';
labelsToApply = {
myFirstLabel: ['key1', 'key2', 'key3'],
anotherLabel: ['key4', 'key5', 'key6'],
lastLabel: ['key7', 'key8', 'key9', 'key10', 'key11'],
}
function getLabels(str, labels) {
var appliedLabels = [];
$.each(labels, function(labelName, keywords) {
$.each(keywords, function() {
if(str.search(this) >= 0) {
appliedLabels.push(labelName);
return false;
}
});
});
return appliedLabels;
}
alert(getLabels(stringToSearch, labelsToApply));
In plain old Javascript I would use something like this:
var stringToSearch = 'this string needs to be key2 searched key4';
var Keywords = function(keywords, label) {
this.keywords = keywords;
this.label = label;
}
var keywords1 = new Keywords(['key1', 'key2', 'key3'], 'keys 1-3');
var keywords2 = new Keywords(['key4', 'key5', 'key6'], 'keys 4-6');
var keywordsArray = [ keywords1, keywords2 ];
for (var i=0; i <keywordsArray.length; i++) {
var keywordsEntry = keywordsArray[i];
for(var j=0; j <keywordsEntry.keywords.length; j++) {
// here you got the index of the occuring keyword
if(stringToSearch.indexOf(keywordsEntry.keywords[j]) > 0) {
// now do sth. with the label
alert(keywordsEntry.label);
}
}
}
(Definitely not very well coded, but this is meant to give you a start.)
Or possibly this, since it's unclear what you want:
stringsToSearch = ['this string needs to be searched', '...']
keywords = {
label1: {
keys: ['key1', 'key2', 'key3'],
matches: []
},
label2: {
keys: ['key4', 'key5', 'key6'],
matches: []
},
label3: {
keys: ['key7', 'key8', 'key9', 'key10', 'key11'],
matches: []
}
}
$.each(keywords, function(labelName, label) {
$.each(stringsToSearch, function(_, stringToSearch) {
$.each(label.keys, function(_, key) {
if(stringToSearch.search(key) >= 0) {
label.matches.push(stringToSearch);
return false;
}
});
});
});
精彩评论