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

151
Visualizações
How to find index of first duplicate in array in Javascript?

    const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

I need to create the function indexOfRepeatedValue (array). Use numbers that are stored in the variable numbers.

I should create a variable firstIndex in this function. In the for loop, check which number repeats first and assign its index to firstIndex. Then write this variable to the console - outside of the for loop.

I came up with this idea It doesn't work at all. I'm lost, some piece of advice?

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(array) {
  let firstIndex;
  for (let i = 0; i < array.length; i++)
    if (firstIndex.indexOf(array[i]) === -1 && array[i] !== '');
  firstIndex.push(array[i]);
  return firstIndex;
}

console.log(
  indexOfRepeatedValue(numbers)
)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Start by making firstIndex an array: let firstIndex = [];

Then make sure the i is not outside the scope you used since you use let.

You end the statement with a semicolon, that means the loop never does the next line

Then return the first number found that is in your new array

Note JS Arrays start at 0, so the result is 3, since the second number 2 is in the 4th place

I have kept my code as close to yours as possible.

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(array) {
  let firstIndex = [];
  for (let i = 0; i < array.length; i++) {
    if (firstIndex.indexOf(array[i]) !== -1) { // we found it
      console.log("found",array[i], "again in position", i)
      console.log("The first of these is in position",numbers.indexOf(array[i]))
      
      
      return i; // found - the function stops and returns
      // return numbers.indexOf(array[i]) if you want the first of the dupes   
    }
    firstIndex.push(array[i]); // not found
  }
  return "no dupes found"
}

console.log(
  indexOfRepeatedValue(numbers)
)

There are many more ways to do this

Javascript: How to find first duplicate value and return its index?

about 4 years ago · Juan Pablo Isaza Relatório

0

Start by initializing firstIndex:

let firstIndex = [];

Use the following to find the index of each repeated element:

if( array.slice(0,i).includes(array[i]) ) {
    firstIndex.push( i );
}

If you need the absolute first index of a repeat:

return firstIndex[0];
//Please note that if this is your goal then you do not even need the variable firstIndex, nor do you need to run through the whole loop.

If you need indices of all repeated elements:

return firstIndex;

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(array) {
  let firstIndex = [];
  for (let i = 0; i < array.length; i++)
    if( array.slice(0,i).includes(array[i]) ) {
      firstIndex.push(i);
    }
  return firstIndex[0];
}

console.log(
  indexOfRepeatedValue(numbers)
)

NOTE

Alternatively, you can use Array#map to get index of repeated values then use Array#filter to retain only those indices, the first [0] is what you're lookin for.

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];

const indexOfRepeatedValue = arr => 
    arr.map((a,i) => arr.slice(0,i).includes(a) ? i : -1)
    .filter(i => i > -1)[0];
    
console.log( indexOfRepeatedValue( numbers ) );

about 4 years ago · Juan Pablo Isaza Relatório

0

You could take an object for storing the index of a value and return early if the index exist.

function indexOfRepeatedValue(array) {
    let firstIndex = {};
    for (let i = 0; i < array.length; i++) {
        if (firstIndex[array[i]] !== undefined) return firstIndex[array[i]];
        firstIndex[array[i]] = i;
    }
    return -1;
}

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];
console.log(indexOfRepeatedValue(numbers));

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