Estoy tratando de comparar dos matrices (que contienen 3 enteros) y devolver una matriz de mensajes de sugerencia que se ajusta a la lógica
-Presione "Casi" cuando 1 dígito y la posición coincidan en la matriz
-presione "no del todo" cuando 1 dígito coincida pero en una posición diferente
-presione "incorrecto" cuando no coincidan los dígitos
Ejemplo de arreglos:
Array1 = [2,7,6] ReferenceArray= [2,9,7] Hint= [“Almost”, “Not Quite”];Código que tengo hasta ahora:
function check( array1, referenceArray ) { let hint=[]; for(i=0;i<referenceArray.length;i++){ for (j=0;j<Array1.length;j++){ //value and position match if ((referenceArray[i] && reference.indexOf[i]) === (Array1[j] && Array1.indexOf[j])) { return hint.push('almost'); } //value matches but not position else if(( referenceArray[i] ===Array1[j]) && !(referenceArray.indexOf[i]===Array1.indexOf[j] )){ return hint.push('not quite'); } }// end of Array1 iteration } // end of reference interation // if all values and position match if(referenceArray===Array1){ return hint.push("correct"); } //if no values match else if (referenceArray!==Array1){ return hintArray.push("incorrect"); }Hice este código, dime si funciona o no 😁
const array1 = [2,7,6] const ReferenceArray = [2,9,7] function compareArrays(arr){ let perfect = true for(let i = 0; i < ReferenceArray.length; i++){ if(ReferenceArray[i] != arr[i]) { perfect = false break } } if(perfect) return 'correct' let hint = [] for(let i = 0; i < ReferenceArray.length; i++){ if(arr[i] == ReferenceArray[i]) hint.push('Almost') else if(ReferenceArray.includes(arr[i])) hint.push('Not Quite') } if(hint.length > 0) return hint return 'incorrect' } console.log(compareArrays(array1))Usaría algunos métodos Array incorporados para ayudar a lograr esto: every() , map() y findIndex() .
Generalmente evito usar .push() porque muta la matriz. El código inmutable es agradable de leer 😉
const check = (array, referenceArray) => { if (array.every((val, index) => val === referenceArray[index] )) { return ['Correct'] } const allHints = array.map((val, index) => { const refArrayIndex = referenceArray.findIndex(refVal => val === refVal); if (refArrayIndex === index) { return 'Almost' } if (refArrayIndex !== -1) { return 'Not Quite' } return undefined }); const hints = allHints.filter((hint) => hint !== undefined); if (hints.length > 0) { return hints; } return ['Incorrect'] }; const hints = check([2,7,6],[2,9,7]); console.log('hints', hints)