const twoD = [ 'rnbqkbnr', 'pppppppp', '8', '8', '4P3', '8', 'PPPP1PPP', 'RNBQKBNR' ]Tengo una matriz 2d que se ve así. ¿Cómo puedo reemplazar cada número con la misma cantidad de caracteres?
Rendimiento esperado:
[ 'rnbqkbnr', 'pppppppp', 'oooooooo', 'oooooooo', 'ooooPooo', 'oooooooo', 'PPPPoPPP', 'RNBQKBNR' ]Intenté este código, sin embargo, recibí este error:
TypeError: Cannot assign to read only property '0' of string 'rnbqkbnr'
twoD.map((row, i) => { row.split("").map((col, j) => { if (isNaN(twoD[i][j])) { twoD[i][j] = "o".repeat(twoD[i][j]); } }); });En realidad, es una matriz 1D hasta que divide sus elementos en símbolos.
const data = ['rnbqkbnr', 'pppppppp', '8', '8', '4P3', '8', 'PPPP1PPP', 'RNBQKBNR']; const result = data.map(row => row.split('') .map(char => isNaN(char) ? char : 'o'.repeat(char)) .join('')); console.log(result); .as-console-wrapper{min-height: 100%!important; top: 0}Si el carácter que desea usar para reemplazar sus números es fijo, entonces podría usar Array.map para hacer algo como esto:
const inputArr = [ 'rnbqkbnr', 'pppppppp', '8', '8', '4P3', '8', 'PPPP1PPP', 'RNBQKBNR' ]; // given example input const replChar = "o"; // character to put in place of numbers let outputArr = inputArr.map((inputStr) => { // passing empty string as the delimiter results in an array of characters. let charArray = inputStr.split(""); let newChars = charArray.map((character) => { // loop over every character and return a string const nums = "1234567890"; if(nums.includes(character)) { // replace numbers with n letters. let number = parseInt(character); return replChar.repeat(number); } return character; }); return newChars.join(""); // merge into string });También puedes hacer esto con un bucle for:
const inputArr = [ 'rnbqkbnr', 'pppppppp', '8', '8', '4P3', '8', 'PPPP1PPP', 'RNBQKBNR' ]; // given example input const replChar = "o"; // character to put in place of numbers let outputArr = []; for(var i = 0; i < inputArr.length; i++) { let inputStr = inputArr[i]; // passing empty string as the delimiter results in an array of characters. let charArray = inputStr.split(""); let newChars = ""; for(var j = 0; j < charArray.length; j++) { let character = charArray[j]; // loop over every character and return a string const nums = "1234567890"; if(nums.includes(character)) { // replace numbers with n letters. let number = parseInt(character); newChars += replChar.repeat(number); } else { newChars += character; } } outputArr.push(newChars) }También quiero mencionar que cuando se trata de escalar estas soluciones, puede haber posibles mejoras. Si el rendimiento es importante para usted en este problema, puede valer la pena mirar algunas de las siguientes publicaciones y, potencialmente, hacer sus propios puntos de referencia: