En un escenario donde tengo una matriz 2d como esta:
[ [0,1,4,2,2,5,5,0], [1,1,4,4,2,2,5,3], [1,6,6,6,7,7,3,3], ]Y deseo abstraer el mismo número en una única matriz 2d nueva como la siguiente: {cualquiera de las dos}
[ [0,1], [1,1], [1,0] ] [ [2,2,0], [0,2,2] ] [ [0,3], [3,3] ] [ [4,0], [4,4] ] [ [5,5], [0,5] ] [ [6,6,6] ]¿Cómo puedo hacer este tipo de lógica en javascript? Básicamente, necesito tener algún tipo de lógica para generar una matriz multidimensional en la anterior. Imagínese obtener el mismo número de esa matriz 2d.
// Initial Data const arr = [ [0, 1, 4, 2, 2, 5, 5, 0], [1, 1, 4, 4, 2, 2, 5, 3], [1, 6, 6, 6, 7, 7, 3, 3], ]; // Numbers you want to distribute to isolated arrays const numbersForDistribute = [1, 2, 3, 4, 5, 6, 7]; const result = []; for (let n of numbersForDistribute) { // find range within initial array for each number // to determine size of result array for it let minRowIndex = 999; let maxRowIndex = 0; let minColumnIndex = 999; let maxColumnIndex = 0; for (let i in arr) { const row = arr[i]; for (let j in row) { const currentElement = row[j]; if (row[j] === n) { if (i < minRowIndex) { minRowIndex = i; } if (i > maxRowIndex) { maxRowIndex = i; } if (j < minColumnIndex) { minColumnIndex = j; } if (j > maxColumnIndex) { maxColumnIndex = j; } } } } const resultForN = []; // build result array of specific size for each number for (let i = minRowIndex; i <= maxRowIndex; i++) { resultForN.push([]); for (let j = minColumnIndex; j <= maxColumnIndex; j++) { resultForN[resultForN.length - 1].push(arr[i][j] === n ? n : 0); } } result.push(resultForN); } console.log(result); .as-console-wrapper {max-height: 100% !important;top: 0;} .as-console-row::after {display: none !important;}