Estoy tratando de split una cadena en una matriz con cada iteración de mi for-loop . Como si una cadena fuera 1234 , entonces quiero dividirla ['12','34'] .
Quiero dividir esta cadena en diferentes formas. Como ['1','2','3','4'] , ['123','4'] , etc. Pero no sé cómo puedo hacerlo.
The string "31173" can be split into prime numbers in 6 ways: [3, 11, 7, 3] [3, 11, 73] [31, 17, 3] [31, 173] [311, 7, 3] [311, 73] let k=1; for(let i=0; i<inputStr.length; i++){ if(k<inputStr.length){ // split string let splittedNums=inputStr.split('',i+k); for(let j=0; j<splittedNums.length; j++){ if(isPrime(splittedNums[j])) result.push([splittedNums[j]]); } } k++; } Intenté usar la función split() pero, como aprendí de los documentos , usará un límite para dividir la cadena y devolverla. Entonces, no funcionará así.
Quiero dividir y verificar si el número es primo o no y luego insertarlo en la matriz. Entonces, al final, obtendré los subarreglos que contienen números primos.
¿Cómo puedo dividir una cadena y luego convertirla en una matriz como esta en javascript?
Una de la solución. Traté de explicar los pasos en el comentario pero solo para resumir.
const str = "12345678"; // split the array const strArr = str.split(""); // loop through the str array and split with a character got by index const splitedStr = strArr.map((each, index) => { // this will split the string by index char but we will lose the separator passed const withoutSeparator = str.split(str[index]); const lastIndex = withoutSeparator.length - 1; // get last element of array // to get the separator back. // basically we are appending the separator char to last item of the array withoutSeparator[lastIndex] = str[index] + withoutSeparator[lastIndex]; return withoutSeparator; }); console.log({ splitedStr });Producción
{ splitedStr: [ [ '', '12345678' ], [ '1', '2345678' ], [ '12', '345678' ], [ '123', '45678' ], [ '1234', '5678' ], [ '12345', '678' ], [ '123456', '78' ], [ '1234567', '8' ] ] }