从另一个数组中的条件替换数组中的元素

Replace element in Array from condition in another array

我正在使用 Javascript 从另一个数组中的条件替换数组中的元素。 我还需要最终输出以从任何被替换的元素中删除“”。

我有一个数组 tagArray,它为给定的句子生成词性 theSentenceToCheck,它看起来像这样。

tagArray DET,ADJ,NOUN,VERB,ADP,DET,ADJ, NOUN ,ADP,DET,ADJ,NOUN

theSentenceToCheck The red book is in the brown shelf in a red house

我能够编写一些有效的东西并生成所需的输出,但它有点冗余和完全意大利面条。 我查看了类似的问题并尝试了其他使用 filter、map 的方法但没有成功,特别是关于如何使用这些方法并删除替换元素的“”。

这是我的方法

var grammarPart1 = "NOUN";
var grammarPart2 = "ADJ";
var posToReplace = 0;

function assignTargetToFillIn(){
   var theSentenceToCheckArrayed = theSentenceToCheck.split(" ");
   var results = [];
     var idx = tagArray.indexOf(grammarPart1);
     var idx2 = tagArray.indexOf(grammarPart2);
   while (idx != -1 || idx2 != -1) {
      results.push(idx);
      results.push(idx2)
      idx = tagArray.indexOf(grammarPart1, idx + 1);
      idx2 = tagArray.indexOf(grammarPart2, idx2 + 1);
      posToReplace = results;
    
}
const iterator = posToReplace.values();
for (const value of iterator) {
    theSentenceToCheckArrayed[value] ="xtargetx";
  }
  var addDoubleQuotesToElements = "\"" + theSentenceToCheckArrayed.join("\",\"") + "\"";
  var addDoubleQuotesToElementsArray = addDoubleQuotesToElements.split(",");
/**This is where I remove the "" from element replaced with xtargetx*/
 const iterator2 = posToReplace.values();
  for (const value of iterator2) {
    addDoubleQuotesToElementsArray[value] ="xtargetx";
   console.log(value);
  }
  
return results;

}

这给了我想要的输出 "The",xtargetx,xtargetx,"is","in","the",xtargetx,xtargetx,"in","a",xtargetx,xtargetx

我想知道什么是更优雅的解决方案或关于其他 JS 函数的指针。

利用数组方法执行此操作的更惯用的正确方法可能是这样的。

  • Array.split(" ") 将句子拆分为单词
  • Array.filter(word => word.length) 删除长度为零的任何值
  • Array.map((word, index) => {...}) 遍历数组并允许您跟踪当前索引值
  • Array.includes(element) 只是测试数组是否包含值
  • Array.join(' ')Array.split(' ')
  • 相反

const tagArray = ["DET", "ADJ", "NOUN", "VERB", "ADP", "DET", "ADJ", "NOUN", "ADP", "DET", "ADJ", "NOUN"];

//  Split on spaces and remove any zero-length element (produced by two spaces in a row) 
const sentanceToCheck = "The red book  is  in the brown shelf in  a  red house".split(" ").filter(word => word.length);

const replaceTokens = ["ADJ", "NOUN"];

const replacementWord = "XXX";

const maskedSentance = sentanceToCheck.map((word, index) => {
  const thisTag = tagArray[index];
  
  if ( replaceTokens.includes(thisTag) ) {
    return replacementWord;
  } else {
    return word;
  }
  
}).join(' ');

console.log( maskedSentance );