gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:58:38 25 4
gpt4 key购买 nike

我有一个这样的字符串数组:

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 = [“鲍勃”,“蒂莫西”,“珍妮”,“蒂莫西”,“杰里米”];

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

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

最佳答案

使用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 .

关于javascript - 检查一个数组的字符串是否作为另一个数组字符串的一部分出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38090659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com