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

150
Visualizações
Why is the findIndex method showing second occurance too?

Basically the idea is that my code chooses a random element from an array. That element is the arr[i].answer and is placed at the end of that array. Then i want to make the first occurrence of that answer as an *. I used the findIndex method as i thought that the first occurrence of my answer will become the * however both first occurrence and the last element have become an asterix.

Here is the code

arr.forEach(element => {
              arr[i].answer = arr[i].sequence[rndElement];
              arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;

              function isFirst(element, index, array) {
                return element === arr[i].answer;
                }

                let index = arr[i].sequence.findIndex(isFirst);
                arr[i].sequence[index] = "*";

              
          });

Above is the necessary code, below is all the code for reference

const arr = [];
    const input = document.getElementById('answer').value;
    const rndElement = Math.floor(Math.random() * 6);


    function displaySeq() {
        var i = 0;
        while (arr.length < 21) {
            const rndInt = Math.floor(Math.random() * 50);
            const iterator = Math.floor(Math.random() * (8 - 3 + 1)) + 3;
          arr[i] = {
              sequence: [rndInt],
              answer: 7,
              guess: []
          };

          let j = iterator;
          while (arr[i].sequence.length < 7) {
              arr[i].sequence.push(rndInt + j);
              j+=iterator;
          }

        arr.forEach(element => {
              arr[i].answer = arr[i].sequence[rndElement];
              arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;

              function isFirst(element, index, array) {
                return element === arr[i].answer;
                }

                let index = arr[i].sequence.findIndex(isFirst);
                arr[i].sequence[index] = "*";

              
          });
          i++;

       }  
        console.log(arr);
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, let me prove that findIndex works like you expect:

console.log([2, 1, 3, 4, 5, 6, 1].findIndex(item => item === 1))

Now, let's see what happens if you repeatedly apply findIndex while replacing your items:

let foo = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

for (let element of foo) {
    foo[foo.findIndex(item => item === element)] = "*";
}

console.log(foo);

So, how do you avoid overriding items that were overriden:

let foo = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2];
let replacedItems = [];

for (let element of foo) {
    if (replacedItems.indexOf(element) < 0) {
        replacedItems.push(element);
        foo[foo.findIndex(item => item === element)] = "*";
    }
}

console.log(foo);

So, what is the problem that you have? The problem is that you replace your item with * and then search for the same item in the same array when it was already replaced at its former first index, so it's current first index is at a higher position, particularly the last one in your example.

What was the solution? We keep track of the item whose index was already found and avoid doing similar replaces.

about 4 years ago · Juan Pablo Isaza 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