Too Colline
Too Colline

Reputation: 100

Replace values in an array dynamically

I have a scenario like this. Say: let a = [2,5,6] and let b = [1,2,3,4,5,6,7,8]. Array b is displayed in boxes and revealed when one clicks any of the boxes. What I am trying to do is, when one clicks on any box and the value is the same as any value in array a, I replace the value with other unique values and if they're not the same I display as it is. e.g. If I click a box that has a value of 2 or 5 or 6 i replace the values with the other values.

A minimal example is:

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>

Upvotes: 0

Views: 1059

Answers (2)

Manikant Gautam
Manikant Gautam

Reputation: 3591

You can try with random numbers if found in first array i.e a

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>

Upvotes: 1

Caleb Rotich
Caleb Rotich

Reputation: 653

Use indexOf() to locate the position of the element you want to replace.

Then use splice() together with the index you got to remove that element.

Then use splice() again to insert a new value to the same index.

Check the documentation of each method above to understand their syntax.

Upvotes: 1

Related Questions