2016-06-29 29 views
1

我有一個字符串,像這樣的數組:檢查數組的字符串顯示爲另一個陣列的字符串的一部分

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中的每個字符串,看它們是否包含names數組中的任何名稱。

只要找到名稱匹配,它應該做兩件事情:

  1. 按名稱的answerKey陣列像這樣:

    VAR answerKey = [ 「鮑勃」, 「蒂莫西「, 」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" 
]; 

我熟悉檢查字符串中的子串而不是當子是一個數組和字符串反對進行檢查是另一個。任何幫助將是非常讚賞:))

+0

看起來像家庭工作! –

回答

1

使用array.prototype.maparray.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

1

檢查,如果這個工程:

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

預期輸出數組就在這裏。

0

在這種情況下你需要做的是使用嵌套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], '?')) 
    } 
    } 
} 
0
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); 
相關問題