javascript - 下划线返回数组中对象的索引,其中单词存在于对象内的句子中

标签 javascript arrays search underscore.js indexof

我有一个数组,里面有这样的数组;

    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"]
];

如果 line[4] 正是搜索语句,例如“A man is Walking”,则使用 Underscore,我可以在“lines”内获取一个数组。将返回行[0];

所以我希望能够只用一个单词搜索这些句子(行),比如“Walking”应该匹配并返回“lines”中的第一个数组,因为有一个句子包含该单词。

_.some(lines, function(array){
            var result = (array[4] == 'walking' && array[4]);
        if (result !== false){
                console.log(result);
            } 
});

我如何修改这个下划线函数,或者是否应该使用正确的函数,或者如果有的话,即使它没有下划线,请提出建议。

最佳答案

假设你没有 ES6 的 find 功能,用简单的 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"]]
 }

关于javascript - 下划线返回数组中对象的索引,其中单词存在于对象内的句子中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154830/

相关文章:

javascript - 使用 Javascript 更改按钮文本

android - 搜索小部件中的自定义建议 (Android ICS)

python - 正则表达式结束对特定字符的搜索

algorithm - 在 O(n) 时间内找到 n x n 矩阵中的局部最小值

javascript - 密码的正则表达式必须包含至少八个字符、至少一个数字以及大小写字母和特殊字符

javascript - 如果文件不存在则创建文件,然后将日志写入其中

javascript - 为什么我必须在类中使用 foo() 而不是函数 foo() ?

java - 4-sum 实现的二次时间

c - 在 C 中的数组中存储十六进制转储

javascript - 如何分配多维数组中的单个元素 (JavaScript)