我有一个像这样的数组的数组;
var lines = [
["1","1","1","A man is walking."]
,["1","1","2","Noooo he's not, no way!"],
["1","1","3","You can't see that far can you?"],
["1","1","4","I can, he stopped, he's looking right at us"]
];
使用Underscore我可以在里面找到一个阵列" line"如果第[4]行恰好是搜索句子,比如,"一个人正在走路。"会返回行[0];
所以我希望能够只用一个单词来搜索这些句子(行),比如" Walking"应匹配并返回'行中的第一个数组'因为那里有一个包含单词的句子。
_.some(lines, function(array){
var result = (array[4] == 'walking' && array[4]);
if (result !== false){
console.log(result);
}
});
如何修改此下划线功能,或者如果我应该使用正确的功能,或者如果有的话,即使它没有下划线,请建议。
答案 0 :(得分:1)
_.some
返回一个布尔值。您需要filter
通过查看搜索字词是否在字符串中来获得匹配结果。索引从0
开始,因此您需要检查索引3而不是4。
工作示例:
var lines = [
["1", "1", "1", "A man is walking."],
["1", "1", "2", "Noooo he's not, no way!"],
["1", "1", "3", "You can't see that far can you?"],
["1", "1", "4", "I can, he stopped, he's looking right at us"]
];
var input = document.getElementById('search');
var output = document.getElementById('output');
input.onkeyup = function (event) {
var value = this.value;
var results = _.filter(lines, function (array) {
return array[3].indexOf(value) > -1;
});
var indexes = _.map(results, function(array) {
return lines.indexOf(array);
});
output.innerHTML = '<pre>Indexes: ' + JSON.stringify(indexes) + '</pre><pre>' + JSON.stringify(results, null, 2) + '</pre>';
};
&#13;
<script src="//cdn.jsdelivr.net/lodash/2.1.0/lodash.compat.js"></script>
<input type="text" id="search" placeholder="Search">
<output id="output"></output>
&#13;
答案 1 :(得分:1)
假设您没有找到ES6的奢侈品,请使用简单的javascript:
var lines = [
["1","1","1","A man is walking."],
["1","1","2","Noooo he's not, no way!"],
["1","1","3","You can't see that far can you?"],
["1","1","4","I can, he stopped, he's looking right at us"]
];
function lineSearch(arr, term) {
var indices = arr.map(function(innerArr, index) {
return innerArr[3].indexOf(term) > -1 ? index : null;
}).filter(function(x) {
return x !== null;
});
var results = arr.map(function(innerArr, index) {
return innerArr[3].indexOf(term) > -1 ? innerArr : null;
}).filter(function(x) {
return x !== null;
});
return {indices: indices, results: results};
}
console.log(lineSearch(lines, "can"));
应该给:
{
indices: [2, 3],
results: [["1", "1", "3", "You can't see that far can you?"], ["1", "1", "4", "I can, he stopped, he's looking right at us"]]
}