What is the best way to identify and replace duplicate elements within an array?

Greetings, website visitors! I am facing a major dilemma with my hangman game.

Here's the deal - I have a word bank:

       wordBank = ["pizza", "pie", "cookie", "candy", "salad", "chicken", "pork", "burger", "fries"]

To start off, I randomly select a word from the word bank and convert it into an array:

randomChosenWord = wordBank[round(random(wordBank.length - 1))].split('')

Additionally, I have an array that contains placeholders equal to the length of the chosen word. When I click on one of the letter buttons, it replaces the corresponding placeholder in this array with the selected letter:

 this.click = function() {
            if (mouseX > this.x - 10 && mouseX < this.x + 10 && mouseY > this.y - 10 && mouseY < this.y + 10) {
                if (randomChosenWord.includes(this.letter)) {               
                lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)
                }

For instance, let's say the random word is "Pizza."

The array representing the chosen letters will initially be displayed as "- - - - -" (matching the length of Pizza).

If I press the 'z' button, the placeholders at the respective indexes where 'z' appears in the word will be replaced. So, it would show up as "- - z - -".

While this functionality is effective, I aim to replace all placeholders within index positions that contain 'z,' showcasing it as "- - z z -".

Could anyone advise me on identifying duplicated elements in an array and substituting them?

Answer №1

To modify the random word, iterate through its length and compare each letter to the selected one. If a match is found, update the character at that position.

for(let i = 0; i < randomChosenWord.length; i++) {
  if(randomChosenWord[i] === this.letter){
    lettersChosen.splice(i, 1, this.letter);
  }
}

This code snippet above effectively replaces the line of code:

lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)

Answer №2

An efficient method:

lettersChosen.split('').map(function (letter, index) {
    return randomChosenWord[index] === this.letter ? this.letter : letter;
}).join('')

Breaking down the lettersChosen into separate letters, looping through with array.map to substitute matching letters, and finally merging them back into a string.

Answer №3

To convert this line:

if (randomChosenWord.includes(this.letter)) {
into a while loop.

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

"Adding an express route after your app has already started listening - a step-by-step guide

I am looking for a way to automatically set up routing in Express. Currently, I am able to scan a directory and manually add routes from all the available files. These routes can also be updated if changes are made in the route file. delete require.cache[ ...

sent a data entry through ajax and performed validation using jquery

Is there a solution to validating the existence of an email value using ajax after validation work is completed? Despite attempting to check for the email value and display an alert if it exists, the form continues to submit regardless. See below for the ...

how can I use jQuery to disable clickable behavior in HTML anchor tags?

Here is the HTML code I am working with: (note -: I included j library on the top of page ) <div class="WIWC_T1"> <a href="javascript:void(0);" onClick="call_levelofcourse();popup('popUpDiv1')">Level of Course</a> </di ...

What is the best method for concealing a Link React component entirely?

I have implemented a sidebar feature with settings that allow the user to toggle the visibility of desired sections. Here is an example of how this component appears: <List> {section.elements.map((subsection) => ( <ListItem key={subsection ...

Transmit an array in a post request with Node.js using the application/x-www-form-urlencoded content type

After attempting to send a post request to an API with post parameters as an array, I encountered difficulties. Here is how it can be done using cURL: curl http://localhost:3000/check_amounts -d amounts[]=15 \ -d amounts[]=30 I then tried to ach ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

What could be the reason for Express not retrieving my external CSS file?

The console consistently displays the message: GET http://localhost:8000/public/stylesheets/mystyle.css. Upon examining the image attached below, it is evident that this path is incorrect. I utilized WebStorm to create the href attribute for the CSS. app ...

Assembly selectively displays output

My objective is to input 8 values and create two 2X2 arrays using assembly language. However, when I execute the code, it prompts me for specific values but then throws an error. What could be causing this issue? Also, I need to work with double precisio ...

Tips for confirming a date format within an Angular application

Recently, I've been diving into the world of Angular Validations to ensure pattern matching and field requirements are met in my projects. Despite finding numerous resources online on how to implement this feature, I've encountered some challenge ...

"Exploring the Power of Asynchronous Promises within a Switch Statement in

My current controller setup is as follows: app.controller('myController', function ($scope, myService) { $scope.pageData = {}; myService.promiseGetDataFromServer() .then(function (response) { $scope.pageData = response ...

Setting a variable in a v-tab using Vuetify now only takes 2 easy clicks!

I'm currently utilizing Vuetify and vuejs to develop a tab system with 3 tabs. The tabs are being switched dynamically by binding to the href of a v-tab. Each time I click on a tab, the value of the speed variable is modified. However, I'm encoun ...

Using the key from the parent ng-repeat to filter ng-repeat

Here is an example: <div class="row" ng-repeat="(key, value) in sections"> <h5>{{ value }}</h5> <ul> <li ng-repeat="item in $parent.items | filter: key">{{ item.name }} -- {{ item.section }}</li> < ...

Homepage WordPress Bootstrap Carousel malfunctioning

I am facing an issue with autoplaying a carousel on my WordPress page. The code for the carousel is as follows: <div class="swiper-container services-slider swiper-container-horizontal" data-cols="3" data-autoplay="1"> <div class="swiper-wr ...

Executing search bar capability through the use of AJAX and HTTP requests in JavaScript

I am currently working on implementing a search feature that will locate data based on the user's query. Specifically, I want to create a search bar in my HTML that can search for book titles stored in my database accessible through GET requests. Alth ...

What is the best way to restrict event handling to only occur once every X seconds using jQuery or JavaScript?

Is there a way to limit handling the event of a rapidly-firing keypress to once per X seconds using jQuery or vanilla JavaScript? Check out this jsfiddle that demonstrates rapid keypress firing without any limiting on the handling: View here ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

Matching the serialized name dynamically using gson

While working with the wikipedia API data, I am facing a challenge in dealing with the changing serialized name on each new search request. The serialized name always corresponds to the first item in the "pages" array (1156934). For instance, when using th ...

JavaScript Subscribe / Unsubscribe Button

I am trying to create a simple JavaScript program that allows users to like and dislike content. However, I am new to JavaScript and finding it a bit challenging. Basically, when the user clicks on the Follow button, the "countF" variable should increase ...

Oops! The system encountered a problem while trying to identify the value `Han` for the property `Script

I'm attempting to extract Chinese characters from a string. According to this particular answer, the following code snippet should work: const nonChinese = /[^\p{Script=Han}]/gimu; const text = "asdP asfasf这些年asfagg 我开源的 几 ...

Issue with Node Canvas/Resemble.js: The image provided has not finished loading during the load operation

Recently, I encountered a challenge while trying to utilize Resemble.js in a node environment. Despite some initial complications with installing canvas/cairo due to OS X Mavericks/XQuarts and Homebrew issues, I eventually succeeded. After making signific ...