检查一个数组的字符串是否作为另一个数组字符串的一部分出现

Check if an Array's strings appear as a part of another array's strings

我有一个字符串数组,如下所示:

var inputArray= [ 
    "Bob Johnson goes to the zoo",
    "Timothy Smith likes to eat ice-cream",
    "Jenny wants to play with her friends",
    "There is no one in the room to play with Timothy",
    "Jeremy Jones has been sleeping all day"
 ];

...和另一个类似这样的名称数组:

var names = [
"bob johnson",
"bob",
"timothy smith",
"timothy",
"jenny sanderson",
"jenny",
"jeremy jones",
"jeremy"
];

...我想做的是检查 inputArray 中的每个字符串,看看它们是否包含名称数组中的任何名称。

每当找到名称匹配时,它应该做两件事:

  1. 将姓名推送到 answerKey 数组,如下所示:

    var answerKey = [ "bob", "timothy", "jenny", "timothy", "jeremy" ];

和 2. 推送名称替换为“?”的字符串像这样到另一个数组(输出):

var output = [
"? goes to the zoo",
"? likes to eat ice-cream",
"? wants to play with her friends",
"There is no one in the room to play with ?",
"? has been sleeping all day"
];

我熟悉检查字符串中的子字符串,但不熟悉子字符串在一个数组中而要检查的字符串在另一个数组中的情况。任何帮助将不胜感激:))

检查这是否有效:

var output = [];
for(var c in inputArray){
  output[c] = inputArray[c].toLowerCase();
  for(var o in names){
    output[c] = output[c].replace(names[o],"?");
  }
}

预期的输出数组就在这里。

在这种情况下,您需要做的是使用嵌套 for 循环,然后检查子字符串。

var answerKey = [], output = [];
for(var i = 0; i < inputArray.length; i++){
  for(var j = 0, len = names.length; j < len; j++){
    if(inputArray[i].toLowerCase().indexOf(names[j]) > -1){
      answerKey.push(names[j])
      output.push(inputArray[i].toLowerCase().replace(names[j], '?'))
    }
  }
}
var output = new Array();
names.forEach(function(field, index) {

    inputArray.forEach(function(key, val) {
          var str1 = key.toUpperCase();
          var str2 = field.toUpperCase();;
          var stat  = str1.contains(str2);
          if(stat == true){
            newArray.push(str1.replace(str2,"?"));
          }

    });
});
console.log(output);

使用array.prototype.map and array.prototype.filter寻求帮助:

var inputArray = [
  "Bob Johnson goes to the zoo",
  "Timothy Smith likes to eat ice-cream",
  "Jenny wants to play with her friends",
  "There is no one in the room to play with Timothy",
  "Jeremy Jones has been sleeping all day"
];

var names = [
  "Bob Johnson",
  "Bob",
  "Timothy Smith",
  "Timothy",
  "Jenny Sanderson",
  "Jenny",
  "Jeremy Jones",
  "Jeremy"
];

var answers = [];
var outputArr = inputArray.map(function(row){
   var matches = names.filter(function(name){ return row.indexOf(name) > -1 });
   matches.forEach(function(match){ answers.push(match); row = row.replace(match, '?')});
   return row;
});

console.log('answers: ' + answers);
console.log('outputArr: ' + outputArr);

顺便说一句,如果名称数组是小写的,只需使用 toLowerCase.

JSFIDDLE.