Updating elements within an array on the fly

In this scenario, let's consider two arrays: array A = [2, 5, 6] and array B = [1, 2, 3, 4, 5, 6, 7, 8]. The values of array B are initially hidden within boxes and become revealed when clicked. The goal is to replace certain values in array B with unique values when they match any value in array A, otherwise display them as they are. For example, if a box containing a value of 2, 5, or 6 is clicked, those values should be replaced with other unique values.

Here is a basic example using Vue.js:


          new Vue({
            el: "#app",
            data: {
              a: [2, 5, 6],
              b: [1, 2, 3, 4, 5, 6, 7, 8]
            },
            methods: {
              replaceNumber() {
                // function to replace the values
              }
            }
          })
        

          body {
            background: #20262E;
            padding: 20px;
            font-family: Helvetica;
          }

          #app {
            background: #fff;
            border-radius: 4px;
            padding: 20px;
            transition: all 0.2s;
          }

          .numbers {
            display: flex;
          }

          li {
            list-style-type: none;
          }
        

          <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
          <div id="app">
            <h2>Numbers:</h2>
            <br/>
            <ul class="numbers">
              <li v-for="num in a">
                {{ num }}
              </li>
            </ul>
            <br/>

            <template>
              <button @click="replaceNumber" v-for="number in b">
                {{ number }}
              </button>
            </template>
          </div>
        

Answer №1

Find the element you need to replace by using indexOf().

Next, utilize splice() with the obtained index to eliminate that element.

Afterwards, employ splice() once more to insert a new value at the same index.

Refer to the documentation for each method mentioned above in order to grasp their syntax.

Answer №2

If you want to experiment with random numbers that are present in the first array, use this code snippet:

var a = [2,5,6] 
 var b = [1,2,3,4,5,6,7,8]
 a.forEach(function(e){
    $("#aDiv").append(`<h2>${e}</h2>`);
 })
 
  b.forEach(function(e){
    $("#bDiv").append(`<h2 class="seconddiv">${e}</h2>`);
 });
 
 $(".seconddiv").on('click',function(){
    let val= $(this).html();
    if(a.includes(parseInt(val))){
      var  uniqueNo = 0;
       do {
          uniqueNo=getRandomInt(0,10);
       }
        while (a.includes(parseInt(uniqueNo)));
       $(this).html(uniqueNo);
    }
 })
 
let getRandomInt= (x,y)=>x+(y-x+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
#aDiv,#bDiv{
 color:yellow;
 background-color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="maindiv">
     <div   id="aDiv">
  
     </div>
    <div id="bDiv" style="margin-top:50px;">
  
     </div>
</div>

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

Count the number of URL segments using JavaScript and jQuery

Can anyone suggest an efficient method to count the number of segments in a URL using JavaScript/jQuery? For instance: www.myexampleurl.com/section1/section2/section3 should output 3 ...

What is the best way to execute AJAX requests in a loop synchronously while ensuring that each request is completed

I am looking to implement an AJAX loop where each call must finish before moving on to the next iteration. for (var i = 1; i < songs.length; i++) { getJson('get_song/' + i).done(function(e) { var song = JSON.parse(e); addSongToPlayl ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...

In ReactJs, what is the best way to load a new component when a button is clicked?

In ReactJs, I have developed a main component known as MainPage using Material-UI. import React from 'react'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import CssBaseline from & ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

Is it possible to retrieve the IMEI number of a mobile phone using expo?

Currently working on developing a mobile app with React Native using Expo. I need to figure out a way to access the client's mobile IMEI number and display it in the front end of the app. Unsure of how to accomplish this task. Is there a method to do ...

The commitment to Q ensures that errors and exceptions are effectively communicated

Here is a code snippet that I am using to transform a traditional nodejs function into a promise-based one: Object.defineProperty(Function.prototype, "toPromise", { enumerable: false, configurable: false, writable: false, value: function ...

Tips for delivering a heartfelt message when a user adds an item

import React from 'react'; import { useForm } from "react-hook-form"; import { toast } from 'react-toastify'; const AddStorage = () => { const { register, handleSubmit } = useForm(); const submitData = data => ...

Tips for preventing a NodeJS script from crashing due to timeout being exceeded

Here is the issue I am encountering: I am attempting to scrape a website's content using NodeJS and puppeteer. Sometimes, my code halts with a Timeout Exceeded error. Is there a way for me to handle this timeout by implementing a function that will e ...

"Put Phonegap on hold for a bit and disable landscape mode

I am currently using Phonegap to develop an Android game. My project includes a lobby feature where players can search for opponents and engage in chat with other players. Once a player has found their opponent, they can commence playing the game together ...

Having trouble resolving a setInterval problem with JavaScript?

Yesterday, I learned about the setInterval function which allows me to execute a task or function after a specific amount of time. While I have successfully implemented the interval in my code, it keeps adding new lines with the date each time. What I re ...

Make the card change to gray when clicked using Bootstrap

Is it possible to achieve a common function in an infinite list using HTML, CSS, JS, jQuery (on the user's side) where an item will be grayed out after being clicked? How can we implement this effect? 1.) When the user clicks on the card element htt ...

A guide to utilizing asynchandler within a class in Node.js

I'm currently in the process of converting my routers into a class structure, but I'm facing a challenge when trying to wrap the asyncHandler function inside the class. Can anyone provide guidance on how to achieve this? userController.js const ...

What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing { "CYLINDER": 2986, "HYDRAULIC": 1421, "JACKS": 84, "INSTALLATION": 119, "REAR": 61, "JACK": 334, "TUBE": 1, "FEED": 114, "ASSEMBLY": 326, "DCS": 2 ...

Add the component view to the webpage's body section

Using Angular 7 and ngx-bootstrap 4.0.1 Dependencies: "bootstrap": "3.3.7", "bootstrap-colorpicker": "2.5.1", "bootstrap-duallistbox": "3.0.6", "bootstrap-markdown": "2.10.0", "bootstrap-progressbar": "0.9.0", "bootstrap-slider": "9.8.0", "bootstrap-tags ...

Using the Grails asset-pipeline with an external JavaScript library

In transitioning from Grails 2 to Grails 3, I am facing the challenge of managing my JavaScript files with the asset-pipeline plugin. The issue lies in using external libraries such as globalize and ajax-solr, which are large and consist of multiple interd ...

Submit the form and additional information in a single AJAX request in Django

Seeking assistance with a straightforward task. The objective is to utilize AJAX POST to move data from a form along with additional information. The challenge lies in extracting this data from the form later on, as it constitutes an entire line. $(func ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Attempting to iterate through and retrieve the names listed in the table

I have a code that I need help with in extracting names from td elements using jQuery. In certain instances, if the td is empty, I want to merge the left-side td with the 5 right-side tds because the first td on the right side is empty and the second td c ...

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...