Home » vue » Replace values in an array dynamically

Replace values in an array dynamically

Posted by: admin November 26, 2021 Leave a comment


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">
  <ul class="numbers">
    <li v-for="num in a">
    <button @click="replaceNumber" v-for="number in b">
    {{ number }}


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.


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]
    $("#bDiv").append(`<h2 class="seconddiv">${e}</h2>`);
    let val= $(this).html();
      var  uniqueNo = 0;
       do {
        while (a.includes(parseInt(uniqueNo)));
let getRandomInt= (x,y)=>x+(y-x+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="maindiv">
     <div   id="aDiv">
    <div id="bDiv" style="margin-top:50px;">