Swapping values in an array based on conditions specified in a different array

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.

Answer №1

A more idiomatic approach to achieve this using array methods can be demonstrated as follows.

  • Array.split(" ") - Splits a sentence into words
  • Array.filter(word => word.length)
    - Eliminates any element with zero length
  • Array.map((word, index) => {...})
    - Iterates through the array while tracking the current index value
  • Array.includes(element) - Verifies if the array contains the specified value
  • Array.join(' ') - Reverses the process of Array.split(' ')

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

// Split based on spaces and remove empty elements (resulting from consecutive spaces) 
const sentenceToCheck = "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 maskedSentence = sentenceToCheck.map((word, index) => {
  const thisTag = tagArray[index];
  
  if ( replaceTokens.includes(thisTag) ) {
    return replacementWord;
  } else {
    return word;
  }
  
}).join(' ');

console.log( maskedSentence );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoid altering the Summernote HTML WYSIWYG editor page due to content CSS

We are currently utilizing the Summernote wysiwyg editor to review and preview html content, some of which contains external stylesheet references. This css not only affects Summernote itself but also alters the styling of the parent page where Summernote ...

Exploring the Function Scope within ViewModel

I have been facing an issue while trying to call a function from my ViewModel within a foreach loop. It seems like the function goes out of scope as soon as I call it. Being new to JavaScript, I am struggling to understand why this is happening. Here is t ...

My custom function is not invoking the Firebase function createUserWithEmailAndPassword

The function createUserWithEmailAndPassword is not being triggered within the SignUpUser function when the onClick event occurs. However, it works when I use onClick={signUpUser(email,password)} import React from 'react'; import styled from &apo ...

What is the best way to halt the ticking of this clock in JavaScript?

I can't seem to figure out how to stop this clock using JavaScript Even though I press the stop button, the clock keeps running <!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to halt the clo ...

Exploring Material UI choices and retrieving the selected option's value

Could someone help me with this issue? When I console.log target, the output is as follows: <li tabindex="-1" role="option" id="mui-21183-option-0" data-option-index="0" aria-disabled="false" aria-select ...

JavaScript: Struggles with utilizing a function as an argument and later executing it inside a nested function

I've been struggling with defining a new function, and I need help resolving it. Here's an example that I was initially referencing: Pass arguments into ajax onreadystatechange callback? I wasn't able to find the solution through research, ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

The jQuery scroll functionality is malfunctioning

Could you please assist me in resolving an issue with my scroll effects not working? I have been unable to pinpoint the problem. The code snippet I am using is based on Bootstrap 4. Below is the code snippet in question: //SCROLL EFFECT $(".nav-link" ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Adjust the size of three panels (left, middle, right) using Javascript, ensuring that the middle panel remains unchanged in size

I am a newcomer to JavaScript and currently working with HTML, CSS, and JS files. I have three panels - left, center, and right - that I want to resize. The left panel resizes correctly when dragging the column border. https://i.stack.imgur.com/LxhUX.png ...

Calls to debounced functions are postponed, with all of them running once the waiting timer is complete

Utilizing the debounce function to create a real-time search feature. Researching more on debouncing from https://css-tricks.com/debouncing-throttling-explained-examples/, it seems like the function should control the number of calls made. In my scenario ...

Reduce the size of a JSON file using PHP by replacing strings manually

When attempting to minify a JSON file using str_replace(), I encountered issues with the method not performing as expected. //My goal is to minify a json file using PHP. //I am currently trying to substitute ", {" with ",{" //$result ...

What is the method of using "*" as the value for allowedModules in a jsreport configuration file to enable all modules?

I am having an issue when trying to generate a report using jsreport STUDIO. The error message I received is as follows: An error occurred - Error during rendering report: Unsupported module in scripts: request. To enable require on a particular module, ...

Adding data to a MySQL table using PHP

I am struggling with the code below: for($x=0; $x<=count($_POST["id_k"])-1; $x++) { $db->query("INSERT INTO evaluation (id_e, id_k, id_p, bulan, tahun, k1, k2, k3, k4, k5, k6, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, e1, e2, e3, e4, ...

Using React.js to establish a connection with a database

Can someone help me with connecting my reactjs to mysql? I have already installed mysql and followed the usual instructions, but I keep getting an error "TypeError: mysql.createConnection is not a function". Below are the codes I am working with. import ...

The issue of nested tabs in Bootstrap 3 causing problems with sliders within the main tab has

Hello, I am utilizing Bootstrap 3 tabs. Within the nav-tabs, there are three tab-panes: the first tab contains text only, the second tab includes a slider, and the third tab has nested tabs. However, I encountered an issue where the slider in the nested t ...

Retrieving information from the browser's IndexedDB and then initiating a call to the

Below is the useEffect callback function that I am currently using: import { initDB, useIndexedDB } from "react-indexed-db"; initDB(DBConfig); const db = useIndexedDB("reads"); useEffect(() => { db.getByIndex("hash ...

What are some ways to enhance the speed of my canvas animations?

My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly. Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive? What would be ...

The RefreshIndicator from Material-UI fails to display during the first page load

I am facing an issue with displaying a loading icon during the initial page load. The code appears to be correct to me but for some reason, the loading icon is not showing up. I am utilizing the RefreshIndicator component from material-ui for the loading i ...

Tips for minimizing redundant calls to a JavaScript function

Currently working on an app using php and js. I have a menu sidebar with various items, where clicking on an item loads the corresponding php file into the main container using jQuery's load function. However, there is a critical problem when loading ...