I am currently using Javascript to replace elements in an array based on a condition in another array. In addition, I need the final output to have any instances of "" removed from the replaced elements.
The array tagArray
generates parts of speech for a given sentence theSentenceToCheck
, and it is structured as follows:
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
While I managed to create a functioning solution that produces the desired output, I find it quite convoluted and messy. I have tried utilizing filter and map methods but have not been successful, especially when it comes to removing the "" for the replaced elements.
This is my current approach:
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(",");
const iterator2 = posToReplace.values();
for (const value of iterator2) {
addDoubleQuotesToElementsArray[value] ="xtargetx";
console.log(value);
}
return results;
}
This method provides the desired output:
"The",xtargetx,xtargetx,"is","in","the",xtargetx,xtargetx,"in","a",xtargetx,xtargetx
If you have any suggestions for a more elegant solution or could point me towards other JS functions to explore, it would be greatly appreciated.