Shuffle array typed by the user in javascript?

Asked

Viewed 148 times

0

I want the user to type numbers in the array and, at the click of the button, the paragraph shows the array he typed, but scrambled. The code below does not work, only if it is a fixed array, type : myArray = ['banana','apple','papaya'];

valores = [];
function adicionaInput() {
  var quantidade = document.getElementById('ordenando');
  valores.push(quantidade.value);
  //quantidade.valores = "";  
}

function embaralhaArray() {
  //valores.sort((elem1,elem2)=>Math.random() - Math.random());
  document.getElementById("valores").innerHTML = valores.sort((elem1,elem2)=>Math.random() - Math.random());
}
        <input type="text" id="ordenando">
        <button type="button" id="add" onclick="adicionaInput();">Add </button>
        <button type="button" id="display" onclick="embaralhaArray();">Mostrar</button>

        <div id='valores'></div>

  • See if this helps: https://answall.com/a/406059/137387

  • "but scrambled" you mean the same values, but in a different order?

1 answer

0

I’m using the Fisher-Yates algorithm for random values, if I’ve helped

valores = [];
function adicionaInput() {
  var quantidade = document.getElementById('ordenando');
  valores.push(quantidade.value);
  //quantidade.valores = "";  
}

function embaralhaArray() {
  var atual = valores.length, tmpVal, iAlea;

  
  while (0 !== atual) {


   iAlea= Math.floor(Math.random() * atual);
   atual -= 1;

   tmpVal= valores[atual];
   valores[atual] = valores[iAlea];
   valores[iAlea] = tmpVal;
  }

  document.getElementById("valores").innerHTML = valores;
}
        <input type="text" id="ordenando">
        <button type="button" id="add" onclick="adicionaInput();">Add </button>
        <button type="button" id="display" onclick="embaralhaArray();">Mostrar</button>

        <div id='valores'></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.