si alguien puede señalar o simplemente dar una pista de lo que hice mal, sería muy apreciado. Entonces la tarea es:
Dadas 2 cadenas, a y b, devuelva el número de posiciones en las que contienen la misma longitud 2 subcadena. Entonces, "xxcaazz" y "xxbaaz" dan como resultado 3, ya que las subcadenas "xx", "xx", "aa" y "az" aparecen en el mismo lugar en ambas cadenas.
function('xxcaazz', 'xxbaaz') debería devolver 3
function('abc', 'abc') debería devolver 2
función('abc', 'axc') debería devolver 0
Mi código:
function stringMatch(a, b){ // convert both strings to arrays with split method let arrA = a.split("") let arrB = b.split("") // create 2 empty arrays to feel in with symbol combinations let arrOne = []; let arrTwo = []; // loop through the first array arrA and push elements to empty arrayOne for ( let i = 0; i < arrA.length ; i++ ) { arrOne.push(arrA[i]+arrA[i+1]) } // loop through the first array arrB and push elements to empty arrayTwo for ( let i = 0; i < arrB.length ; i++ ) { arrTwo.push(arrB[i]+arrB[i+1]) } // create a new array of the matching elements from arrOne and arrTwo let newArray = arrOne.filter(value => arrTwo.includes(value)) // return the length 0f the newArray - that's supposed to be the answer return newArray.length }¡Gracias por la ayuda!
En la última iteración de sus bucles, no habrá un carácter "siguiente", arrB[i+1] no estará definido. La forma más sencilla de resolverlo es hacer un bucle solo hasta el penúltimo carácter, o hasta i < arrB.length - 1 .
for ( let i = 0; i < arrB.length - 1; i++ ) { arrTwo.push(arrB[i]+arrB[i+1]) }p.ej..
console.log(stringMatch('xxcaazz', 'xxbaaz')); //should return 3 console.log(stringMatch('abc', 'abc')); // should return 2 console.log(stringMatch('abc', 'axc')); //should return 0 function stringMatch(a, b){ // convert both strings to arrays with split method let arrA = a.split("") let arrB = b.split("") // create 2 empty arrays to feel in with symbol combinations let arrOne = []; let arrTwo = []; // loop through the first array arrA and push elements to empty arrayOne for ( let i = 0; i < arrA.length -1 ; i++ ) { arrOne.push(arrA[i]+arrA[i+1]) } // loop through the first array arrB and push elements to empty arrayTwo for ( let i = 0; i < arrB.length - 1; i++ ) { arrTwo.push(arrB[i]+arrB[i+1]) } // create a new array of the matching elements from arrOne and arrTwo let newArray = arrOne.filter(value => arrTwo.includes(value)) // return the length 0f the newArray - that's supposed to be the answer return newArray.length }Como beneficio adicional, aquí está mi propia solución ...
console.log(stringMatch('xxcaazz', 'xxbaaz')); //should return 3 console.log(stringMatch('abc', 'abc')); // should return 2 console.log(stringMatch('abc', 'axc')); //should return 0 function stringMatch(a, b){ var matches = 0; for(let i=a.length-1; i--;){ let s1 = a.substring(i, i+2); let s2 = b.substring(i, i+2); if(s1 == s2) matches++; } return matches; }