【问题标题】:Replace element in Array from condition in another array从另一个数组中的条件替换数组中的元素
【发布时间】:2021-12-12 00:58:56
【问题描述】:

我正在使用 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 函数的指针。

【问题讨论】:

    标签: javascript arrays replace


    【解决方案1】:

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

    • 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 );

    【讨论】:

    • 正是我想要的。感谢您的帮助和详细的回答/解释!
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 2013-07-04
    • 2019-12-20
    • 2014-11-07
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多