Estoy usando Javascript para reemplazar elementos en una matriz desde una condición en otra matriz. También necesito que el resultado final elimine el "" de cualquier elemento que se reemplace.
Tengo una matriz, tagArray que genera partes del discurso para una oración dada theSentenceToCheck y se ve así.
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
Pude escribir algo que funciona y genera el resultado deseado, pero es un poco redundante y espagueti total. Miré preguntas similares y probé otros enfoques usando filtro, mapa sin éxito, especialmente sobre cómo usar esos enfoques y eliminar el "" para elementos reemplazados.
este es mi enfoque
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;}
Esto me da el resultado deseado "The",xtargetx,xtargetx,"is","in","the",xtargetx,xtargetx,"in","a",xtargetx,xtargetx
Me preguntaba cuál sería una solución más elegante o sugerencias sobre qué otras funciones JS analizar.
Una forma idiomáticamente más correcta de hacer esto aprovechando los métodos de matriz podría ser así.
Array.split(" ") divide una oración en palabrasArray.filter(word => word.length) elimina cualquier valor cuya longitud sea ceroArray.map((word, index) => {...}) itera sobre la matriz y le permite realizar un seguimiento del valor del índice actualArray.includes(element) simplemente prueba que la matriz incluye el valorArray.join(' ') hace lo contrario de 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 );