Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
How to output random array entry -- then remove that item from the array afterwards?

In my program, when the user clicks a button, an item (a string) from an array gets randomly selected, and is then outputted to the user.

My goal is to introduce some kind of "remove this item from the array after displaying to the user" functionality, to prevent repeat outputs. That way, each time they're viewing a fresh item, and not seeing the same ones over and over again.

Here is my v1 version of coding this:

Array1 = [] // the full array of all items is contained in here.
Array2 = [] // this is the post-display holding bay for items the user has seen already.

After outputting an item to the user from Array 1? That item will be added to Array 2. BEFORE displaying any array items to a user? It will cross-reference the randomly selected item against the full list of items in Array2, basically using IF/ELSE IF logic. Something like this:

for (let i = 0; i < NumberOfArray2Items; i++) {
  if (Array1ItemToDisplay === Array2[i]) {
    NumberOfMatches = j++ // basically, increment a numerical variable, so that any value
      // greater than 0 indicates, yes, it's been outputted to the user before
  }
}

if (NumberOfMatches === 0) {
  DisplayCurrentArrayItem();
} else if (NumberOfMatches > 0) {
  SelectAnotherArrayItemToDisplay();
}

That's a rough version of what I have in mind, and frankly it sounds like a terrible solution because it requires two very lengthy programmatic steps:

  1. Looping over every single item in Array2 for cross-referencing
  2. Potentially running that dozens, maybe hundreds of times, if it continues to find matches each time it runs that block of code.

Is there some simpler, faster method of cross-refencing an item against an entire array? Or perhaps cross-referencing both arrays against each other, to only leave the remaining items that don't match, and then select from that intermediate list of items that hasn't yet been displayed?

These arrays will contain tens of thousands of items, so my concern is, as presently written, this code will take forever to execute. Is there some simpler, faster, more efficient solution I'm not seeing?

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Here you go, each time the button is clicked a random element from the array is shown. That element is then removed - so no duplicates are shown.

const data = ['foo', 'bar', 'bat', 'baz'];

document.getElementById('btn').addEventListener("click", e => {
  if(!data.length) return;
  const idx = Math.floor(Math.random() * data.length);
  console.log(data[idx]);
  data.splice(idx, 1);
});
<button id=btn>click</button>

I also added a check to make sure that when there are no unique items left nothing happens, not sure if this is what you wanted or not. If not - remove the line if(!data.length) return;

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda