通过抽象另一个数组中的一些数据来形成新的二维数组

Forming new 2d array by abstract some data in the other array

在我有这样一个二维数组的场景中:

[
  [0,1,4,2,2,5,5,0],
  [1,1,4,4,2,2,5,3],
  [1,6,6,6,7,7,3,3],
]

我希望将相同的数字抽象成一个新的二维数组,如下所示:{任一个}

[
  [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]
]

如何在javascript中实现这种逻辑? 基本上,我需要某种逻辑来在上面生成 任一个 多维数组。想象一下从那个二维数组中得到相同的数字。

// 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;}