我们如何找到并计算以下句子中出现的次数?
sentences = [
'black im yello'
'green black and white'
'green green green green green greenana'
'i have no color'
]
find_char = [
'green',
'black',
'white'
]
应该返回
output = {
'sentence 1' : 1 // just black
'sentence 2' : 3 // green black white
'sentence 3' : 6 // 5 green and green in 'green'ana
'sentence 4' : 0
}
这是我当前的代码
var output = {};
for (var i = sentences.length - 1; i >= 0; i--) {
var output_tmp = {};
var occurance = 0;
for (x = 0; x < find_char.length; x++) {
j = 0;
output_tmp[find_char[x]] = 0;
// search if sentences then -1, if > -1 then there is a match
while ((j = sentences[i].indexOf(find_char[x], j)) > -1) {
output_tmp[find_char[x]]++;
j++
}
occurance += output_tmp[find_char[x]];
}
output[i] = { 'sentence_no': i, 'occurance' : occurance};
}
有没有更好的方法来做到这一点?