Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda