const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];Necesito crear la función indexOfRepeatedValue (array) . Use números que están almacenados en los números de variables.
Debería crear una variable firstIndex en esta función. En el bucle for , comprueba qué número se repite primero y asigna su índice a firstIndex . Luego escriba esta variable en la consola, fuera del bucle for.
Se me ocurrió esta idea No funciona en absoluto. Estoy perdido, ¿algún consejo?
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) )Comience por hacer de firstIndex una matriz: let firstIndex = [];
Luego, asegúrese de que i no esté fuera del alcance que usó, ya que usa let.
Termina la declaración con un punto y coma, eso significa que el ciclo nunca hace la siguiente línea
Luego devuelva el primer número encontrado que está en su nueva matriz
Tenga en cuenta que las matrices JS comienzan en 0, por lo que el resultado es 3, ya que el segundo número 2 está en el cuarto lugar
He mantenido mi código lo más cerca posible del tuyo.
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) )Hay muchas más formas de hacer esto
Javascript: ¿Cómo encontrar el primer valor duplicado y devolver su índice?
Comience inicializando firstIndex :
let firstIndex = [];Use lo siguiente para encontrar el índice de cada elemento repetido:
if( array.slice(0,i).includes(array[i]) ) { firstIndex.push( i ); }Si necesita el primer índice absoluto de una repetición:
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.Si necesita índices de todos los elementos repetidos:
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) )NOTA
Alternativamente, puede usar Array#map para obtener el índice de valores repetidos y luego usar Array#filter para retener solo esos índices, el primer [0] es lo que está buscando.
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 ) );Puede tomar un objeto para almacenar el índice de un valor y regresar antes si el índice existe.
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));